app.config(function($routeProvider, $locationProvider) {
	$routeProvider.
	when('/order', {
			templateUrl: 'order/list.html',
			controller: 'orderListController'
		})
		.when('/order/company', {
            templateUrl: 'order/company_order_list.html',
            controller: 'companyOrderListController'
        })
        .when('/orderCallCenter', {
            templateUrl: 'order/list.html',
            controller: 'orderCallCenterListController'
        })
        .when('/orderEdit/order_id/:order_id', {
            templateUrl: 'order/edit.html',
            controller: 'orderEditController'
        })
		.when('/grabPool', {
            templateUrl: 'order/grab_pool.html',
            controller: 'grabPoolListController'
        })
        .when('/orderEdit/supervise/:order_id', {
	        templateUrl: "order/supervise.html",
	        controller: 'orderEditController'
	    })
		.when('/orderEdit/visit/:order_id', {
        templateUrl: "order/visit.html",
        controller: 'orderEditController'
      	})
        .when('/orderEdit/end/:order_id', {
        templateUrl: "order/end.html",
        controller: 'orderEditController'
      	})
		.when('/orderEdit/add', {
	        templateUrl: "order/order.html",
	        controller: 'orderAddController'
	    })
		.when('/orderEdit/detail/:order_id', {
            templateUrl: 'order/detail.html',
            controller: 'orderEditController'
        })
        .when('/order/yuyue', {
            templateUrl: "order/yuyue.html",
            controller: 'orderReservationController'
        })
        .when('/order/grab/detail/:order_id', {
            templateUrl: "order/grab_detail.html",
            controller: 'orderDetailController'
        });
});


function orderService($http, $location) {

	return {
		
		list: function(data,limit, page, app_id, fn) {
			var param = {
				limit: limit,
				page: page,
				start_time:(data != '' && data != undefined)?data.start_time:'',
	            end_time:(data != '' && data != undefined)?data.end_time:'',
	            company:(data != '' && data != undefined)?data.company:'',
	            status:(data != '' && data != undefined)?data.status:'',
	            //score:(data != '' && data != undefined)?parseInt(data.score):'',
                record_manager_id:(data != '' && data != undefined)?data.record_manager_id:'',
	            serviceType1:(data != '' && data != undefined && data.serviceType1!=undefined)?data.serviceType1:undefined,
	            serviceType2:(data != '' && data != undefined && data.serviceType2!=undefined)?data.serviceType2:undefined,
	            serviceType3:(data != '' && data != undefined && data.serviceType3!=undefined)?data.serviceType3:undefined,
	            order_id:(data != '' && data != undefined)?data.order_id:'',
	            name:(data != '' && data != undefined)?data.username:'',
	            address:(data != '' && data != undefined)?data.address:'',
                phone:(data != '' && data != undefined)?data.phone:'',
                card_number:(data != '' && data != undefined)?data.card_number:'',
	            more_status:(data != '' && data != undefined)?data.more_status:'',
	            selected_company_name : (data != '' && data != undefined)?data.selected_company_name:'',
                archives_code : (data != '' && data != undefined)?data.archives_code:''
			};
            //if( data != '' && data != undefined && data.serviceType3!=undefined ){
            //    param.serviceType3 =  data.serviceType3;
            //}
			baas_yl.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/orderList/count',
                'data' : param,
                'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
                }
       		 });
		}
		,serviceList :function(code,app_id,fn){
         	baas_yl.call({
                'http': $http,
                'method': 'get',
                'uri': 'console/service/list/'+code,
                'success': function(d) {
                     if (typeof fn == 'function') {
	                    fn(d);
	                }
                }
            });
         }
        ,serviceList2 :function(parent_code,app_id,fn){
         	baas_yl.call({
                'http': $http,
                'method': 'get',
                'uri': 'console/service/list/'+parent_code,
                'success': function(d) {
                     if (typeof fn == 'function') {
	                    fn(d);
	                }
                }
            });
        }
        ,serviceList3 :function(parent_code,app_id,fn){
         	baas_yl.call({
                'http': $http,
                'method': 'get',
                'uri': 'console/service/list/'+parent_code,
                'success': function(d) {
                     if (typeof fn == 'function') {
	                    fn(d);
	                }
                }
            });
        }
        ,setContractProbationInfo :function(data,order_id,fn) {
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'data': data,
                'uri': 'order/order/probation/agreement/' + order_id,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        export: function(data, fn) {
            var data = {
                'start_time':(data != ''&& data != undefined)?data.start_time:'',
                'end_time':(data != ''&& data != undefined)?data.end_time:'',
                'company':(data != ''&& data != undefined)?data.company:'',
                'status':(data != ''&& data != undefined)?data.status:'',
                'score':(data != ''&& data != undefined)?parseInt(data.score):'',
                'serviceType1':(data != ''&& data != undefined && data.serviceType1!=undefined)?data.serviceType1:'',
                'serviceType2':(data != ''&& data != undefined && data.serviceType2!=undefined)?data.serviceType2:'',
                'order_id':(data != ''&& data != undefined)?data.order_id:'',
                'name':(data != ''&& data != undefined)?data.username:'',
                'address':(data != ''&& data != undefined)?data.address:'',
                'phone':(data != ''&& data != undefined)?data.phone:''
            };
            var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
            if(manager!=undefined && manager!=""){
                data.selected_company_code = manager.company_code;
            }
            if(manager!=undefined&&manager.isPension){
                data.selected_manager_group_id = manager.manager_group_id;
            }
            ////社区业务员
            if(typeof manager!= undefined && manager.manager_id!=undefined && manager.manager_id != '' && manager.type_code=='commService'){
                data.record_manager_id=manager.manager_id;
            }
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/orderList/export',
                'data' : data,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
        ,add: function( data,app_id, fn) {
			var data = {
				serviceType1 : $('#serviceType1').val(),
                serviceType2 : $('#serviceType2').val(),
                serviceType3 : $('#serviceType3').val(),
                username:$('#name').val(),
                phone:$('#phone').val(),
                name:$('#name').val(),
                address:$('#address').val(),
                time:$('#time').val(),
                detail:$('#detail').val(),
                to_app_id:friend_app_id
			};
		
			baas_yl.call({
				'http': $http,
				'method': 'post',
				'uri': 'order/order/addOrder',
				'data': data,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});
		}
        ,update :function(data,fn){
			var data = {
	           'company':data.company,
	           'reason':data.reason,
	           'status':data.status,
	        	'order_id':data.order_id,
	            'name':data.name,
	            'phone':data.phone,
	            'address':data.address,
	            'serviceType1':data.serviceType1,
	            'serviceType2':data.serviceType2,
	            'detail':data.detail,
	            'duban_time':data.time,
	            'duban_info':(data.duban != undefined && data.duban != '')?data.duban.info:'',
	            'duban_name':(data.duban != undefined && data.duban != '')?data.duban.name:'',
	            'score':parseInt(data.score),
	            'comments':data.comments
	        };
	         baas_yl.call({
		        'http': $http,
		        'method': 'post',
		        'data':data,
		        'uri': 'order/orderList/update',
		        'success': function(d) {
		        	if (typeof fn == 'function') {
						fn(d);
					}
		        }
			});
		}
        ,returnVisit : function( order_id, visit, fn ){
            baas_yl.call({
                'http': $http,
                'method': 'post',
                'uri' : 'order/order/' + order_id + '/return_visit',
                'data' : visit,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
		termination :function(order_id,data,fn){
            baas_yl.call({
                'http': $http,
                'method': 'post',
                'data':data,
                'uri': 'order/order/termination/order/'+order_id,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },serviceListAll :function(code,fn){

            var data = {
                'code':(code != ''&& code  != undefined)?code:''
            };
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'data':data,
                'uri': 'order/orderList/serviceList',
                'success': function(d) {

                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },

        // orderService of uhome by Nie
        getServiceListByCode: function (code, fn) {
            var data = {
                code: (typeof code != 'undefined' && code != null) ? code : ''
            };
            baas_jz.call({
                http: $http,
                method: 'post',
                data: data,
                uri: 'order/orderList/serviceList',
                success: function (json) {
                    if (typeof fn == 'function') {
                        fn(json);
                    }
                }
            });
        },
        getOrderDetail: function (data, fn) {
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'data': data,
                'uri': 'order/orderList/info',
                'success': function (ison) {
                    if (typeof fn == 'function') {
                        fn(json);
                    }
                }
            });
        },
        addOrder: function (data, app_id, fn) {


            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/order/addOrder',
                'data': data,
                'success': function (json) {
                    if (typeof fn == 'function') {
                        fn(json);
                    }
                }
            });
        },
        searchCompanyList: function(serviceType3_code, fn) {
            var data={
                serviceType3_code:serviceType3_code,
                limit:1000
            }
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'data':data,
                'uri': 'company/company/list',
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        getCompany: function(app_id, fn) {
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'order/orderList/companyList',
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        searchList: function(data,  fn) {
            if(typeof data.serviceType3_code=="undefined"){
                delete data.serviceType3_code;
            }

            if(typeof data.username!="undefined" && data.username!="" ){
                data.name = data.username;
            }
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/orderList/count',
                'data' : data,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
	};
}
function rsvService( $http ){ //预订模块， 由话务员看到
    return {
        list : function(param, fn){
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'order/reservation/list',
                'data':param,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        edit : function( id, dataParams, app_id, fn){
            var data = {
                phone : dataParams.phone,
                name  : dataParams.name,
                serviceType1_code  : dataParams.serviceType1_code,
                serviceType1_title : dataParams.serviceType1_title,
                serviceType2_code  : dataParams.serviceType2_code,
                serviceType2_title : dataParams.serviceType2_title
            };
            if(dataParams.status != undefined ){
                data.status = dataParams.status;
            }
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/reservation/edit/' + id,
                'data': data,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },update : function( id, data, app_id, fn){

            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/reservation/edit/' + id,
                'data': data,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
        ,delete : function( id, app_id, fn ){
            var data = {
                id : id
            };
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/reservation/delete' ,
                'data': data,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
        ,serviceLists : function(code, app_id, fn){
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'console/service/list/' + code,
                'success': function(d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
    };
}

app.factory('orderService', ['$http', '$location', orderService]);
app.factory('rsvService', ['$http', rsvService]);
app.controller('grabPoolListController', ['$scope', '$rootScope', '$window', '$location', '$http', '$routeParams','orderService', 'servantService', grabPoolListController]);
app.controller('orderListController', ['$scope', '$window', '$location', '$http', '$routeParams','orderService', orderListController]);
app.controller('orderAddController', ['$scope','$routeParams','$window','$location','$http','orderService', 'callCenterService', orderAddController]);
app.controller('orderEditController', ['$scope', '$window', '$location', '$http', '$routeParams','orderService', orderEditController]);
app.controller('orderReservationController', ['$scope', '$rootScope',  '$window', '$location', '$http', '$routeParams','rsvService', 'orderService',orderReservationController]);
app.controller('orderDetailController', ['$scope', '$window', '$location', '$http', '$routeParams','orderService', orderDetailController]);
app.controller('companyOrderListController', ['$scope','$rootScope', '$window', '$location', '$http', '$routeParams','orderService','servantService', companyOrderListController]);

function companyOrderListController( $scope,$http,$rootScope, $window, $location, $routeParams,orderService,servantService){
    $scope.baas_yl_app_id = baas_yl.app_id;
    $scope.baas_jz_app_id =baas_jz.app_id;
    $scope.reason="";
    $scope.search={
        limit:20,
        page:1
    };
    $scope.order={
        is_trial:0
    };
    var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
    if(manager.isWX){//微信修改
        $scope.search.limit=10;
    }
    $scope.service3_list=[];
    if(manager.company_code!=undefined && manager.company_code!=""){
        $scope.search.more_status='已接单|试工中|服务中|完成|待回访|已回访|终止订单|终止审核';
        $scope.search.selected_company_code=manager.company_code;
        if( manager.serviceType3_code != undefined && manager.serviceType3_code != "" ){
            $scope.search.serviceType3_code= manager.serviceType3_code.join("|");
        }
        for(i=0;i<manager.serviceType3_code.length;i++){
            var obj={
                code:manager.serviceType3_code[i],
                title:manager.serviceType3_title[i]
            }
            $scope.service3_list.push(obj);
        }


    }

    $scope.getserviceType1 = function(code){
        orderService.serviceList(code,function(d){
            $scope.serviceList1 = d.list;
            $scope.order.is_trial="0";
            $scope.serviceList3=[];

        });
    }
    $scope.getserviceType2 = function(code){
        orderService.serviceList(code,function(d){
            $scope.serviceList2 = d.list;
            $scope.filterCompanyList = '';
            $scope.order.is_trial="0";
            $scope.serviceList3=[];
        });
    }
    $scope.getserviceType3 = function(code){
        orderService.serviceList(code,function(d){
            $scope.serviceList3 = d.list;
            $scope.filterCompanyList = [];
            $scope.order.is_trial="0";
        });
    }

    $scope.getserviceType1('0');

    if(manager!=undefined&&manager.isPension){
        $scope.search.selected_manager_group_id=manager.manager_group_id;
    }
    ////社区业务员
    if(typeof manager!= undefined && manager.manager_id!=undefined && manager.manager_id != '' && manager.type_code=='commService'){
        $scope.search.record_manager_id=manager.manager_id;
    }

    $scope.getList = function(){
        orderService.searchList($scope.search,function(json){
            $scope.list = json['list'];
            console.log($scope.list);
            $scope.count = json['count'];
            $scope.currentPage = 1;
            $scope.getPage(json['count']);
        });

    }
    $scope.getList();
    //搜索
    $scope.searchOrder = function(data){
        $scope.search.start_time=angular.element("#start_time").val();
        $scope.search.end_time=angular.element("#end_time").val();
        var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
        if(manager.company_code!=undefined && manager.company_code!=""){
            if( manager.serviceType3_code != undefined && manager.serviceType3_code != "" ){
                if($scope.search.serviceType3_code==""||$scope.search.serviceType3_code==null||$scope.search.serviceType3_code==undefined)
                    $scope.search.serviceType3_code= manager.serviceType3_code.join("|");
            }
        }


        $scope.search.page=1;
        //serviceType3_code: "yanglaobaomu"

        //console.log("==="+$scope.order.serviceType3.code);
        if( typeof $scope.order.serviceType1!="undefined"&&$scope.order.serviceType1!="undefined")
        {
            //delete $scope.search.serviceType1;
            if( typeof $scope.order.serviceType2!="undefined"&&$scope.order.serviceType2!="undefined")
            {
                //delete $scope.search.serviceType2;

                if( typeof $scope.order.serviceType3!="undefined"&&$scope.order.serviceType3!="undefined")
                {
                    $scope.search.serviceType3_code=$scope.order.serviceType3.code;
                    //delete $scope.order.serviceType3;
                }
            }
        }

        //console.log("==="+$scope.search.serviceType3.code);
        orderService.searchList($scope.search,  function(json) {
            $scope.list = json['list'];
            $scope.count = json['count'];
            $scope.currentPage = 1;
            $scope.getPage(json['count']);
        });
    }
    $scope.getCompany = function(){
        orderService.getCompany( $scope.app_id, function(json) {
            $scope.companylist = json.list;
        });
    }
    $scope.getCompany();
    /*分页*/
    $scope.changePage = function(p) {
        $scope.search.page = p;
        orderService.searchList($scope.search, function(json) {
            $scope.list = json.list;
            $scope.count = json.count;
            $scope.currentPage = p;
            $scope.getPage(json.count);
        });
    };
    $scope.getPage = function(count) {
        $scope.pageList = [];
        var limit = $scope.search.limit; //返回的条数
        $scope.totalPage = parseInt(count / limit); //总页数
        $scope.totalPage += count % limit >= 1 ? 1 : 0; //判断页数是否是整数
        var start = ($scope.currentPage - 2) >= 1 ? $scope.currentPage - 2 : 1; //首页
        var end = ($scope.currentPage + 2) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage; //尾页

        $scope.frontdotShow = start > 1 ? true : false; //前面的省略号
        $scope.backdotShow = end < $scope.totalPage ? true : false; //后面的省略号
        for (var i = start; i <= end; i++) {
            $scope.pageList.push({
                number: i,
                active: i == $scope.currentPage ? 'active' : ''
            }); //给点击的按钮添加class
        }
    };

    $scope.cancel = function(order_id){
        var data = {
            'selected_company_code':'',
            'selected_company_name':'',
            'order_id':order_id
        };
        orderService.update(data,function(d){
            if(d){
                $scope.getList();
            }else{
                alert("更新失败");
            }
        });
    };
    $scope.updateOrderStatus_begin=function(order,status){
        if(!order.selected_servant_id||order.selected_servant_id==""||order.selected_servant_id ==undefined){
            alert("请选择服务人员");
            return;
        }
        var data = {
            'status':status,
            'order_id':order.order_id
        };
        orderService.update(data,function(d){
            if(d){
                closeMod();
                $scope.getList();

            }else{
                alert("更新失败");
            }
        });
    }
    $scope.updateOrderStatus = function(order_id,status) {
        var data = {
            'status':status,
            'order_id':order_id
        };
        orderService.update(data,function(d){
            if(d){
                closeMod();
                $scope.getList();

            }else{
                alert("更新失败");
            }
        });
    };
    $scope.delete = function(order_id){
        orderService.delete(order_id, function(json) {
            $scope.searchOrder($scope.search);
        });
    }
    $scope.openWindow=function(order_id){
        $scope.order_id=order_id;
    }

    //set合同信息 by gxl 20150916

    $scope.setContractInfo=function(item){

        console.log(item.name);
        $scope.ContractInfo=item;

    }
    //合同信息传送到接口
    $scope.setContractProbation = function(setInfo,status) {
        setInfo.time2=angular.element('#time2').val();

        console.log("setInfo.number="+setInfo.number);
        console.log("setInfo.time1="+setInfo.time1);
        console.log("setInfo.time2="+setInfo.time2);
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.number == 'undefined' ||
            setInfo.number.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert('协议编号不能为空！');
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.time1 == 'undefined' ||
            setInfo.time1.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert('试工期不能为空！');
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.time2 == 'undefined' ||
            setInfo.time2.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert("试工开始时间不能为空！");
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.name == 'undefined' ||
            setInfo.name.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert("客户姓名不能为空！");
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.address == 'undefined' ||
            setInfo.address.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert("甲方地址不能为空！");
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.selected_company_phone == 'undefined' ||
            setInfo.selected_company_phone.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert("丙方联系方式不能为空！");
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.probation_money == 'undefined' ){

            alert("试工期工资不能为空！");
            return;
        }
        var data = {
            agreement_probation_number:setInfo.number,
            agreement_probation_jia_name:setInfo.name,
            agreement_probation_jia_address:setInfo.address,
            agreement_probation_jia_phone:setInfo.phone,
            agreement_probation_yi_name:setInfo.selected_servant_name,
            agreement_probation_yi_phone:setInfo.selected_servant_phone,
            agreement_probation_bing_name:setInfo.selected_company_name,
            agreement_probation_bing_phone:setInfo.selected_company_phone,
            agreement_service_type:setInfo.serviceType2_title,
            agreement_probation_days:setInfo.time1,
            agreement_probation_start:setInfo.time2,
            agreement_probation_foregift:setInfo.foregift,
            agreement_probation_money:setInfo.probation_money
        };
        orderService.setContractProbationInfo(data,setInfo.order_id,function(d){
            if(d){
                $scope.updateOrderStatus(setInfo.order_id,status);
            }else{
                alert("更新失败");
            }
        });
    };


    $scope.orderAmount=function(money){
        var data={
            settlement_total:money,
            order_id:$scope.order_id,
            status:"待回访"
        }
        orderService.update(data,function(d){
            if(d){
                closeMod();
                $scope.getList();
            }else{
                alert("更新失败");
            }
        });
    }
    $scope.saveBackOrder=function(reason,status){
        if(reason.length==0){
            alert("请填写终止服务\退单原因");
        }else{
            status=status.replace("审核","");

            var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
            var data={
                source:"company",
                username:manager.manager_account,
                reason:reason,
                type:status,
                company_code:manager.company_code,
                company_name:manager.company_name,
                service_station_account:manager.isPension?manager.manager_account:""
            }
            console.log(data);
            orderService.termination($scope.order_id,data,function(d){
                if(d){
                    closeMod();
                    $scope.getList();
                }else{
                    alert("更新失败");
                }
            });


        }
    }
    $scope.getSelCompany=function(order_id){
        $scope.order_id=order_id;
    }
    $scope.saveSelCompany=function(company){
        if(company==undefined || company==""){
            alert("请选择派单企业");
        }else{
            var data = {
                'selected_company_code':company.code,
                'selected_company_name':company.name,
                'status':'待受理',
                'order_id':$scope.order_id
            };
            orderService.update(data,function(d){
                if(d){
                    closeMod();
                    alert("派单成功")
                    $scope.getList();
                }else{
                    alert("更新失败");
                }
            });
        }

    }

    $scope.export = function(data){
        var url = WEB_URL + '/order/orderList/export';

        orderService.export(data,function(d){
            if(d.status){
                $scope.export_url = d.url;
                angular.element('#exportUrl').show();
            }
            else
                alert('网络错误，请重新导出');
        });

    };
    $scope.selServant=function(obj){
        $scope.order=obj;
        $scope.searchOfServant.jobs=obj.serviceType3_code;

    };
    ////////////////////////////从业人员筛选//////////////////////////////

    $scope.selectedPageOfServant = 1;
    $scope.limitOfServant = 5;
    if(manager.isWx){
        $scope.limitOfServant = 4;
    }
    $scope.searchOfServant = {
        verifystatus:"已通过审核"
    };

    $scope.getServantList = function () {
        $scope.selectedPageOfServant = 1;
        manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
        if( manager!=undefined&&manager.isPension){
            $scope.searchOfServant.manager_group_id=manager.manager_group_id;
        }
        $scope.searchOfServant.serviceType3_code=$scope.order.serviceType3_code;
        servantService.searchList($scope.searchOfServant, $scope.limitOfServant, $scope.selectedPageOfServant,$scope.app_id, function( json ){
            $scope.servantList = json['list'];
            $scope.countOfServant = json['count'];
            $scope.currentPageOfServant = 1;
            $scope.getPageOfServant($scope.countOfServant);
        });

    };
    $scope.getPageOfServant = function (count) {
        $scope.pageListOfServant = [];
        var limit = $scope.limitOfServant;
        $scope.totalPageOfServant = parseInt(count / limit);
        $scope.totalPageOfServant += count % limit >= 1 ? 1 : 0;
        var start = ($scope.currentPageOfServant - 2) >= 1 ? $scope.currentPageOfServant - 2 : 1;
        var end = ($scope.currentPageOfServant + 2) <= $scope.totalPageOfServant ? $scope.currentPageOfServant + 2 : $scope.totalPageOfServant;
        for (var i = start; i <= end; i++) {
            $scope.pageListOfServant.push({
                number: i,
                active: i == $scope.currentPageOfServant ? 'active' : ''
            });
        }
    };
    $scope.changePageOfServant = function (page) {
        if (page == 0) {
            page = 1;
        }
        $scope.selectedPageOfServant = page;
        manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
        if( manager!=undefined&&manager.isPension){
            $scope.searchOfServant.manager_group_id=manager.manager_group_id;
        }
        servantService.searchList($scope.searchOfServant, $scope.limitOfServant, $scope.selectedPageOfServant, $scope.app_id, function (json) {
            $scope.servantList = json['list'];
            $scope.countOfServant = json['count'];
            $scope.currentPageOfServant = page;
            $scope.getPageOfServant($scope.countOfServant);
        });
    };

    $scope.selServantWin = function (order) {
        $scope.order = order;
        $scope.searchOfServant = {
            verifystatus: "已通过审核",
            serviceType3_code:order.serviceType3_code
        };
        $scope.getServantList();
    };
    $scope.setServant = function (servant) {
        $scope.order.selected_servant_id = servant.servant_id;
        $scope.order.selected_servant_name = servant.name;
        var data = {
            'servant_id':servant.servant_id,
            'order_id':$scope.order.order_id
        };
        orderService.selServant(data,function(d){
            if(d.status==1){
                alert("服务人员选择成功");
                closeMod();
                $scope.getList($scope.search);
            } else{
                if(d.description){
                    alert(d.description);
                }else{
                    alert( '网络原因，请求失败，请稍后重试' );
                }
            }
        });
    };
    $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
        init();
    });
}

function orderCallCenterListController( $scope, $window, $location, $http,$routeParams,orderService){
	//初始化搜索条件
	$scope.search = {};
	$scope.search.serviceType1 = {};
	$scope.search.serviceType2 = {};
	$scope.search.serviceType3 = {};
	$scope.search.filter_manage_account_id = 'all';

	$scope.selectedPage = 1;
	$scope.limit = 20;

    $scope.setOrderListFilter = function ( filter, page ) {

        if( filter.serviceType1 != undefined && filter.serviceType1 != {} ){
            filter.serviceType1_code = filter.serviceType1;
        }

        if( filter.serviceType2 != undefined && filter.serviceType2 != {} ){
            filter.serviceType2_code = filter.serviceType2;
        }

        if( filter.serviceType3 != undefined && filter.serviceType3 != {} ){
            filter.serviceType3_code = filter.serviceType3;
        }
        filter.filter_manage_account_id = 'all';
        if( filter.record_manager_id != undefined && filter.record_manager_id != '' ){
            filter.filter_manage_account_id = 'mine';
        }

        var ts = sessionStorage.getItem('ts');
        localStorage.setItem(ts + 'orderListFilter', JSON.stringify( filter ) );
        localStorage.setItem(ts + 'orderListPage', page);

    };

    $scope.getOrderListFilter = function ( ) {
        var ts = sessionStorage.getItem('ts');
        var orderListFilter = localStorage.getItem(ts + 'orderListFilter');
        $scope.search = orderListFilter != null ? JSON.parse( orderListFilter ) : {};
        $scope.selectedPage = localStorage.getItem(ts + 'orderListPage');
    };

	$scope.changePage = function (p) {
		var start_time = angular.element("#start_time").val();
		var end_time = angular.element("#end_time").val();
		$scope.data = {
			start_time:(start_time != '' && start_time != undefined)?start_time:'',
			end_time:(end_time != '' && end_time != undefined)?end_time:'',

            card_number:($scope.search != undefined && $scope.search.card_number != undefined && $scope.search.card_number != '' )?$scope.search.card_number:'',
            username:( $scope.search != undefined &&  $scope.search.username != undefined && $scope.search.username != '' )?$scope.search.username:'',
            phone:($scope.search != undefined && $scope.search.phone != undefined && $scope.search.phone != '')?$scope.search.phone:'',
            selected_company_name : ($scope.search != undefined &&  $scope.search.selected_company_name != undefined && $scope.search.selected_company_name != '')?$scope.search.selected_company_name:'',
            status:($scope.search != undefined && $scope.search.status != undefined && $scope.search.status != '' )?$scope.search.status:'',
            company:($scope.search != undefined && $scope.search.company != undefined && $scope.search.company != '')?$scope.search.company:'',
            serviceType1: $scope.search!= null && $scope.search.serviceType1 != null &&typeof $scope.search.serviceType1.code != 'undefined' && $scope.search.serviceType1.code != ''  ? $scope.search.serviceType1.code:undefined,
            serviceType2:$scope.search!= null && $scope.search.serviceType2 != null &&typeof $scope.search.serviceType2.code != 'undefined' && $scope.search.serviceType2.code != ''  ? $scope.search.serviceType2.code:undefined,
            serviceType3:$scope.search!= null && $scope.search.serviceType3 != null &&typeof $scope.search.serviceType3.code != 'undefined' && $scope.search.serviceType3.code != ''  ? $scope.search.serviceType3.code:undefined,

			record_manager_id: (typeof $scope.search.filter_manage_account_id != "undefined" && $scope.search.filter_manage_account_id == "mine") ? $scope.manageId : ""
			//more_status: '待受理|已接单|试工中|服务中|待回访|已删除|订单审核|终止审核|终止订单'
		};
		$scope.selectedPage = p;
        $scope.setOrderListFilter( $scope.data, $scope.selectedPage );
		orderService.list($scope.data, $scope.limit, $scope.selectedPage, friend_app_id, function (json) {
			$scope.list = json.list;
			$scope.count = json.count;
			$scope.currentPage = $scope.selectedPage;
			$scope.getPage(json.count);
		});
	};
	$scope.getPage = function (count) {
		$scope.pageList = [];
		var limit = $scope.limit; //返回的条数
		$scope.totalPage = parseInt(count / limit); //总页数
		$scope.totalPage += count % limit >= 1 ? 1 : 0; //判断页数是否是整数
		var start = ($scope.currentPage - 2) >= 1 ? $scope.currentPage - 2 : 1; //首页
		var end = ($scope.currentPage + 2) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage; //尾页
		$scope.frontdotShow = start > 1 ? true : false; //前面的省略号
		$scope.backdotShow = end < $scope.totalPage ? true : false; //后面的省略号
		for (var i = start; i <= end; i++) {
			$scope.pageList.push({
				number: i,
				active: i == $scope.currentPage ? 'active' : ''
			}); //给点击的按钮添加class
		}
	};

	//搜索

	$scope.filter = function () {
		$scope.changePage(1);
	};
    $scope.openWindow = function(order_id){
        $scope.order_id = order_id;
        angular.element('#back-order-dialog').modal('show') //打开

    }
    $scope.saveBackOrder = function(reason,status){
        if(reason.length==0){
            alert("请填写终止服务\退单原因");
        }else{
            status=status.replace("审核","");
            var manager=$scope.manager;
            var data={
                source:"company",
                username:manager.manager_account,
                reason:reason,
                type:status
            }
            console.log(data);
            orderService.termination($scope.order_id,data,function(d){
                if(d){
                    closeMod();
                    $scope.stopOrder(reason,status,$scope.order_id)
                }else{
                    alert("更新失败");
                    angular.element('#back-order-dialog').modal('hide')
                }
            });
        }
    };
    $scope.stopOrder = function (reason,status,order_id){
        var data = {
            'status':status,
            'reason':reason,
            'order_id':order_id
        };
        baas_yl.call({
            'http': $http,
            'method': 'post',
            'data':data,
            'uri': 'order/order/'+order_id+'/stop/order',
            'success': function(d) {
                if(d){
                    closeMod();
                    $scope.filter();
                    angular.element('#back-order-dialog').modal('hide')
                }else{
                    alert("更新失败");
                    angular.element('#back-order-dialog').modal('hide')
                }
            }
        });
    }
	$scope.cancel = function (order_id) {
		var data = {
			'company': '',
			'order_id': order_id
		};
		baas_yl.call({
			'http': $http,
			'method': 'post',
			'data': data,
			'uri': 'order/orderList/update',
			'success': function (d) {
				if (d) {
					$scope.getList();
				} else {
					alert("更新失败");
				}
			}
		});
	};

    $scope.export_url = '';
    $scope.export_clicked = 0;
	$scope.export = function (orderData, query) {

        $scope.export_clicked = 1;

        var data = {
			'start_time':typeof angular.element("#start_time").val()!="undefined"?angular.element("#start_time").val():"",
			'end_time':typeof angular.element("#end_time").val()!="undefined"?angular.element("#end_time").val():"",
			'company': (orderData != '' && orderData != undefined) ? orderData.company : '',
			'status': (orderData != '' && orderData != undefined) ? orderData.status : '',
			'score': (orderData != '' && orderData != undefined) ? parseInt(orderData.score) : '',
			'serviceType1': (orderData != '' && orderData != undefined && orderData.serviceType1 != undefined) ? orderData.serviceType1.code : '',
			'serviceType2': (orderData != '' && orderData != undefined && orderData.serviceType2 != undefined) ? orderData.serviceType2.code : '',
			//'serviceType3':(data != ''&& data != undefined && data.serviceType3!=undefined)?data.serviceType3:'',
			'order_id': (orderData != '' && orderData != undefined) ? orderData.order_id : '',
			'name': (orderData != '' && orderData != undefined) ? orderData.username : '',
			'address': (orderData != '' && orderData != undefined) ? orderData.address : '',
			'card_number': (orderData != '' && orderData != undefined) ? orderData.card_number : '',
			'selected_company_name': (orderData != '' && orderData != undefined) ? orderData.selected_company_name : '',
			'phone': (orderData != '' && orderData != undefined) ? orderData.phone : ''
			// 'company':'111'
		};
		if (orderData != '' && orderData != undefined && orderData.serviceType3 != undefined) {
			data.serviceType3 = orderData.serviceType3.code;
		}
        $scope.export_url = '';
        baas_yl.call({
			'http': $http,
			'method': 'post',
			'data': data,
			'uri': 'order/orderList/export',
			'success': function (d) {
                if (d.status) {
					$scope.export_url = d.url;
					angular.element('#url').show();
				}
				else
					alert('网络错误，请重新导出');
			}
		});

	};

	//服务类型联动列表
	$scope.serviceType = function (service_id, level, isFirstLoad) {
		orderService.serviceList(service_id, friend_app_id, function (json) {
			if (level == 0) {
				$scope.serviceType1List = [];
				for (var i = 0; i < json.length; i++) {
					if (json[i].title == "养老服务") {
						$scope.serviceType1List.push(json[i]);
					}
				}
				$scope.serviceType2List = [];
				$scope.serviceType3List = [];
				$scope.search.serviceType1 = $scope.serviceType1List[0];
				$scope.serviceType($scope.search.serviceType1.code, 1, isFirstLoad);
			} else if (level == 1) {
				$scope.serviceType2List = json;
				$scope.serviceType3List = [];
				$scope.search.serviceType2 = {};
				$scope.search.serviceType3 = {};
                for(var i = 0; i < json.length; i++){
                    if (json[i].code == $scope.search.serviceType2_code) {
                        $scope.search.serviceType2 = json[i];
                        $scope.serviceType($scope.search.serviceType2_code, 2, isFirstLoad);
                    }
                }
                if (isFirstLoad == 0 && ( $scope.search == undefined || $scope.search.serviceType3_code == undefined || $scope.search.serviceType3_code == '' )) {
                    var lastPage = $scope.selectedPage != undefined ? $scope.selectedPage : 1;
					$scope.changePage( lastPage );
				}
			} else if (level == 2) {
				$scope.serviceType3List = json;
				$scope.search.serviceType3 = {};
                for(var i = 0; i < json.length; i++){
                    if (json[i].code == $scope.search.serviceType3_code) {
                        $scope.search.serviceType3 = json[i];
                    }
                }
                if (isFirstLoad == 0) {
                    var lastPage = $scope.selectedPage != undefined ? $scope.selectedPage : 1;
                    $scope.changePage( lastPage );
                }
			} else if (level == 3) {
				return;
			}
		});
	};
	//$scope.serviceType(0, 0, 0);
    $scope.init = function(){
        $scope.getOrderListFilter();
        $scope.serviceType(0, 0, 0);
    };
    $scope.init();

}

function orderListController( $scope, $window, $location, $http,$routeParams,orderService){
	//初始化搜索条件
	$scope.search = {};
	$scope.search.serviceType1 = {};
	$scope.search.serviceType2 = {};
	$scope.search.serviceType3 = {};
	//$scope.search.filter_manage_account_id = 'all';

	$scope.selectedPage = 1;
	$scope.limit = 20;

    $scope.setOrderListFilter = function ( filter, page ) {

        if( filter.serviceType1 != undefined && filter.serviceType1 != {} ){
            filter.serviceType1_code = filter.serviceType1;
        }

        if( filter.serviceType2 != undefined && filter.serviceType2 != {} ){
            filter.serviceType2_code = filter.serviceType2;
        }

        if( filter.serviceType3 != undefined && filter.serviceType3 != {} ){
            filter.serviceType3_code = filter.serviceType3;
        }
        var ts = sessionStorage.getItem('ts');
        localStorage.setItem(ts + 'orderListFilter', JSON.stringify( filter ) );
        localStorage.setItem(ts + 'orderListPage', page);

    };

    $scope.getOrderListFilter = function ( ) {
        var ts = sessionStorage.getItem('ts');
        var orderListFilter = localStorage.getItem(ts + 'orderListFilter');
        $scope.search = orderListFilter != null ? JSON.parse( orderListFilter ) : {};

        $scope.selectedPage = localStorage.getItem(ts + 'orderListPage');

    };

	$scope.changePage = function (p) {
		var start_time = angular.element("#start_time").val();
		var end_time = angular.element("#end_time").val();
		$scope.data = {
			start_time:(start_time != '' && start_time != undefined)?start_time:'',
			end_time:(end_time != '' && end_time != undefined)?end_time:'',
			card_number:($scope.search != undefined && $scope.search.card_number != undefined && $scope.search.card_number != '' )?$scope.search.card_number:'',
			username:( $scope.search != undefined &&  $scope.search.username != undefined && $scope.search.username != '' )?$scope.search.username:'',
			phone:($scope.search != undefined && $scope.search.phone != undefined && $scope.search.phone != '')?$scope.search.phone:'',
			selected_company_name : ($scope.search != undefined &&  $scope.search.selected_company_name != undefined && $scope.search.selected_company_name != '')?$scope.search.selected_company_name:'',
			status:($scope.search != undefined && $scope.search.status != undefined && $scope.search.status != '' )?$scope.search.status:'',
			company:($scope.search != undefined && $scope.search.company != undefined && $scope.search.company != '')?$scope.search.company:'',
			serviceType1: $scope.search!= null && $scope.search.serviceType1 != null &&typeof $scope.search.serviceType1.code != 'undefined' && $scope.search.serviceType1.code != ''  ? $scope.search.serviceType1.code:undefined,
			serviceType2:$scope.search!= null && $scope.search.serviceType2 != null &&typeof $scope.search.serviceType2.code != 'undefined' && $scope.search.serviceType2.code != ''  ? $scope.search.serviceType2.code:undefined,
			serviceType3:$scope.search!= null && $scope.search.serviceType3 != null &&typeof $scope.search.serviceType3.code != 'undefined' && $scope.search.serviceType3.code != ''  ? $scope.search.serviceType3.code:undefined
			//record_manager_id: (typeof $scope.search.filter_manage_account_id != "undefined" && $scope.search.filter_manage_account_id == "mine") ? $scope.manageId : "",
			//more_status: '待受理|已接单|试工中|服务中|待回访|已删除|订单审核|终止审核|终止订单'
		};
		$scope.selectedPage = p;

        $scope.setOrderListFilter( $scope.data, $scope.selectedPage );

		orderService.list($scope.data, $scope.limit, $scope.selectedPage, friend_app_id, function (json) {
			$scope.list = json.list;
			$scope.count = json.count;
			$scope.currentPage = $scope.selectedPage;
			$scope.getPage(json.count);
		});
	};
	$scope.getPage = function (count) {
		$scope.pageList = [];
		var limit = $scope.limit; //返回的条数
		$scope.totalPage = parseInt(count / limit); //总页数
		$scope.totalPage += count % limit >= 1 ? 1 : 0; //判断页数是否是整数
		var start = ($scope.currentPage - 2) >= 1 ? $scope.currentPage - 2 : 1; //首页
		var end = ($scope.currentPage + 2) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage; //尾页
		$scope.frontdotShow = start > 1 ? true : false; //前面的省略号
		$scope.backdotShow = end < $scope.totalPage ? true : false; //后面的省略号
		for (var i = start; i <= end; i++) {
			$scope.pageList.push({
				number: i,
				active: i == $scope.currentPage ? 'active' : ''
			}); //给点击的按钮添加class
		}
	};

	$scope.filter = function () {
		$scope.changePage(1);
	};
    $scope.openWindow = function(order_id){
        $scope.order_id = order_id;
        angular.element('#back-order-dialog').modal('show') //打开

    }
    $scope.saveBackOrder = function(reason,status){
        if(reason.length==0){
            alert("请填写终止服务\退单原因");
        }else{
            status=status.replace("审核","");
            var manager=$scope.manager;
            var data={
                source:"company",
                username:manager.manager_account,
                reason:reason,
                type:status
            }
            console.log(data);
            orderService.termination($scope.order_id,data,function(d){
                if(d){
                    closeMod();
                    $scope.stopOrder(reason,status,$scope.order_id)
                }else{
                    alert("更新失败");
                    angular.element('#back-order-dialog').modal('hide')
                }
            });
        }
    };
    $scope.stopOrder = function (reason,status,order_id){
        var data = {
            'status':status,
            'reason':reason,
            'order_id':order_id
        };
        baas_yl.call({
            'http': $http,
            'method': 'post',
            'data':data,
            'uri': 'order/order/'+order_id+'/stop/order',
            'success': function(d) {
                if(d){
                    closeMod();
                    $scope.filter();
                    angular.element('#back-order-dialog').modal('hide')
                }else{
                    alert("更新失败");
                    angular.element('#back-order-dialog').modal('hide')
                }
            }
        });
    }
	$scope.cancel = function (order_id) {
		var data = {
			'company': '',
			'order_id': order_id
		};
		baas_yl.call({
			'http': $http,
			'method': 'post',
			'data': data,
			'uri': 'order/orderList/update',
			'success': function (d) {
				if (d) {
					$scope.getList();
				} else {
					alert("更新失败");
				}
			}
		});
	};
    $scope.export_url = '';
    $scope.export_clicked = 0;
	$scope.export = function (orderData, query) {
        $scope.export_clicked = 1;

		var data = {
            'start_time':typeof angular.element("#start_time").val()!="undefined"?angular.element("#start_time").val():"",
            'end_time':typeof angular.element("#end_time").val()!="undefined"?angular.element("#end_time").val():"",
			'company': (orderData != '' && orderData != undefined) ? orderData.company : '',
			'status': (orderData != '' && orderData != undefined) ? orderData.status : '',
			'score': (orderData != '' && orderData != undefined) ? parseInt(orderData.score) : '',
			'serviceType1': (orderData != '' && orderData != undefined && orderData.serviceType1 != undefined) ? orderData.serviceType1.code : '',
			'serviceType2': (orderData != '' && orderData != undefined && orderData.serviceType2 != undefined) ? orderData.serviceType2.code : '',
			//'serviceType3':(data != ''&& data != undefined && data.serviceType3!=undefined)?data.serviceType3:'',
			'order_id': (orderData != '' && orderData != undefined) ? orderData.order_id : '',
			'name': (orderData != '' && orderData != undefined) ? orderData.username : '',
			'address': (orderData != '' && orderData != undefined) ? orderData.address : '',
			'card_number': (orderData != '' && orderData != undefined) ? orderData.card_number : '',
			'selected_company_name': (orderData != '' && orderData != undefined) ? orderData.selected_company_name : '',
			'phone': (orderData != '' && orderData != undefined) ? orderData.phone : ''
			// 'company':'111'
		};
		if (orderData != '' && orderData != undefined && orderData.serviceType3 != undefined) {
			data.serviceType3 = orderData.serviceType3.code;
		}
        $scope.export_url = '';
		baas_yl.call({
			'http': $http,
			'method': 'post',
			'data': data,
			'uri': 'order/orderList/export',
			'success': function (d) {
				if (d.status) {
					$scope.export_url = d.url;
					angular.element('#url').show();
				}
				else
					alert('网络错误，请重新导出');
			}
		});

	};

	//服务类型联动列表
	$scope.serviceType = function (service_id, level, isFirstLoad) {
		orderService.serviceList(service_id, friend_app_id, function (json) {
			if (level == 0) {
				$scope.serviceType1List = [];
				for (var i = 0; i < json.length; i++) {
					if (json[i].title == "养老服务") {
						$scope.serviceType1List.push(json[i]);
					}
				}
				$scope.serviceType2List = [];
				$scope.serviceType3List = [];
				$scope.search.serviceType1 = $scope.serviceType1List[0];
				$scope.serviceType($scope.search.serviceType1.code, 1, isFirstLoad);
			} else if (level == 1) {
				$scope.serviceType2List = json;
				$scope.serviceType3List = [];
				$scope.search.serviceType2 = {};
				$scope.search.serviceType3 = {};
                for(var i = 0; i < json.length; i++){
                    if (json[i].code == $scope.search.serviceType2_code) {
                        $scope.search.serviceType2 = json[i];
                        $scope.serviceType($scope.search.serviceType2_code, 2, isFirstLoad);
                    }
                }
				if (isFirstLoad == 0 && ( $scope.search == undefined || $scope.search.serviceType3_code == undefined || $scope.search.serviceType3_code == '' )) {
                    var lastPage = $scope.selectedPage != undefined ? $scope.selectedPage : 1;
                    $scope.changePage( lastPage );
				}
			} else if (level == 2) {
				$scope.serviceType3List = json;
				$scope.search.serviceType3 = {};
                for(var i = 0; i < json.length; i++){
                    if (json[i].code == $scope.search.serviceType3_code) {
                        $scope.search.serviceType3 = json[i];
                    }
                }
                if (isFirstLoad == 0) {
                    var lastPage = $scope.selectedPage != undefined ? $scope.selectedPage : 1;
                    $scope.changePage( lastPage );
                }
			} else if (level == 3) {
				return;
			}
		});
	};
    $scope.init = function(){
        $scope.getOrderListFilter();
        $scope.serviceType(0, 0, 0);
    };
    $scope.init();

}

//function grabPoolListController($scope, $window, $location, $http, $routeParams, orderService) {
//    $scope.selectedPage = 1;
//    $scope.data = {
//        selectedPage: $scope.selectedPage,
//        page: $scope.page
//    };
//    $scope.limit = 20;
//
//    $scope.getList = function () {
//        orderService.list($scope.limit, $scope.selectedPage, $scope.app_id, function (json) {
//            $scope.list = json['list'];
//            $scope.count = json['count'];
//            $scope.currentPage = 1;
//            $scope.getPage(json['count']);
//        });
//    };
//    $scope.getList();
//
//    /*分页*/
//    $scope.changePage = function (p) {
//        $scope.data.selectedPage = p;
//        orderService.list($scope.limit, p, $scope.app_id, function (json) {
//            $scope.list = json.list;
//            $scope.count = json.count;
//            $scope.currentPage = p;
//            $scope.getPage(json.count);
//        });
//    };
//    $scope.getPage = function (count) {
//        $scope.pageList = [];
//        var limit = 20; //返回的条数
//        $scope.totalPage = parseInt(count / limit); //总页数
//        $scope.totalPage += count % limit >= 1 ? 1 : 0; //判断页数是否是整数
//        var start = ($scope.currentPage - 2) >= 1 ? $scope.currentPage - 2 : 1; //首页
//        var end = ($scope.currentPage + 2) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage; //尾页
//
//        $scope.frontdotShow = start > 1 ? true : false; //前面的省略号
//        $scope.backdotShow = end < $scope.totalPage ? true : false; //后面的省略号
//        for (var i = start; i <= end; i++) {
//            $scope.pageList.push({
//                number: i,
//                active: i == $scope.currentPage ? 'active' : ''
//            }); //给点击的按钮添加class
//            console.log(count);
//        }
//    };
//
//    $scope.cancel = function (order_id) {
//        var data = {
//            'company': '',
//            'order_id': order_id
//        };
//        baas_yl.call({
//            'http': $http,
//            'method': 'post',
//            'data': data,
//            'uri': 'order/orderList/update',
//            'success': function (d) {
//                if (d) {
//                    $scope.getList();
//                } else {
//                    alert("更新失败");
//                }
//            }
//        });
//    };
//}

function grabPoolListController($scope, $rootScope, $window, $location, $http, $routeParams, orderService, servantService) {
    $scope.baas_yl_app_id = baas_yl.app_id;
    var manager = JSON.parse(localStorage.getItem(sessionStorage.getItem("who") + "manager"));
    console.log(manager);
    $scope.search = {
        limit: 20,
        page: 1,
        selected_company_code_all: manager.company_code,
        status: "待受理"
    };
    //if (manager.isWX) {
    //    $scope.search.limit = 10;
    //}
    $scope.manager_company_code = manager.company_code;
    $scope.search.serviceType3_code = (typeof manager.serviceType3_code != 'undefined' && manager.serviceType3_code != "") ? (manager.serviceType3_code).join("|") : "";
    if (typeof manager != 'undefined' && manager.isPension) {
        $scope.search.selected_manager_group_id = manager.manager_group_id;
    }

    $scope.getList = function (obj) {
        orderService.searchList($scope.search, function (json) {
            $scope.list = json['list'];
            console.log($scope.list);
            manager = JSON.parse(localStorage.getItem(sessionStorage.getItem("who") + "manager"));
            $scope.manager = manager;
            angular.forEach($scope.list, function (item, key) {
                $scope.list[key].selected_servant_name = "";
                if (item.selected_company_code == manager.company_code) {
                    $scope.list[key].af = true;
                } else {
                    $scope.list[key].af = false;
                }
                /**
                 * $scope.filter_order 方法为判断订单按钮状态的 方法
                 */
                $scope.list[key].tag = $scope.filter_order(item);
            });

            $scope.count = json['count'];
            $scope.currentPage = 1;
            $scope.getPage(json['count']);
        });
    };
    $scope.getList("init");

    $scope.checked = true;
    //by gxl 20150929 对抢单池订单进行筛选 （显示可抢订单）

    $scope.getNewOrderList = function (obj) {
        if ($scope.checked) {
            $scope.checked = false;
            obj.company_code = manager.company_code;
        } else {
            $scope.checked = true;
            delete $scope.search.company_code;
        }
        orderService.searchList($scope.search, function (json) {
            $scope.list = json['list'];
            manager = JSON.parse(localStorage.getItem(sessionStorage.getItem("who") + "manager"));
            angular.forEach($scope.list, function (item, key) {
                if (item.selected_company_code == manager.company_code) {
                    $scope.list[key].af = true;
                } else {
                    $scope.list[key].af = false;
                }
                $scope.list[key].tag = $scope.filter_order(item);
            });
            $scope.count = json['count'];
            $scope.currentPage = 1;
            $scope.getPage(json['count']);
        });
    };

    /*分页*/
    $scope.changePage = function (p) {
        $scope.search.page = p;
        orderService.searchList($scope.search, function (json) {
            $scope.list = json.list;
            manager = JSON.parse(localStorage.getItem(sessionStorage.getItem("who") + "manager"));
            angular.forEach($scope.list, function (item, key) {
                if (item.selected_company_code == manager.company_code) {
                    $scope.list[key].af = true;
                } else {
                    $scope.list[key].af = false;
                }
                $scope.list[key].tag = $scope.filter_order(item);
            })
            $scope.count = json.count;
            $scope.currentPage = p;
            $scope.getPage(json.count);
        });
    };
    $scope.getPage = function (count) {
        $scope.pageList = [];
        var limit = $scope.search.limit; //返回的条数
        $scope.totalPage = parseInt(count / limit); //总页数
        $scope.totalPage += count % limit >= 1 ? 1 : 0; //判断页数是否是整数
        var start = ($scope.currentPage - 2) >= 1 ? $scope.currentPage - 2 : 1; //首页
        var end = ($scope.currentPage + 2) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage; //尾页

        $scope.frontdotShow = start > 1 ? true : false; //前面的省略号
        $scope.backdotShow = end < $scope.totalPage ? true : false; //后面的省略号
        for (var i = start; i <= end; i++) {
            $scope.pageList.push({
                number: i,
                active: i == $scope.currentPage ? 'active' : ''
            }); //给点击的按钮添加class
            console.log(count);
        }
    };

    $scope.selectedPageOfServant = 1;
    $scope.limitOfServant = 5;
    //if (manager.isWX) {
    //    $scope.limitOfServant = 4;
    //}
    $scope.searchOfServant = {
        servantstatus: "待岗",
        verifystatus: "已通过审核"
    };

    $scope.getServantList = function () {
        $scope.selectedPageOfServant = 1;
        manager = JSON.parse(localStorage.getItem(sessionStorage.getItem("who") + "manager"));
        if (manager != undefined && manager.isPension) {
            $scope.searchOfServant.manager_group_id = manager.manager_group_id;
        }

        servantService.searchList($scope.searchOfServant, $scope.limitOfServant, $scope.selectedPageOfServant, $scope.app_id, function (json) {
            $scope.servantList = json['list'];
            //console.log($scope.servantList);
            $scope.countOfServant = json['count'];
            $scope.currentPageOfServant = 1;
            $scope.getPageOfServant($scope.countOfServant);
        });
    };
    $scope.getPageOfServant = function (count) {
        $scope.pageListOfServant = [];
        var limit = $scope.limitOfServant;
        $scope.totalPageOfServant = parseInt(count / limit);
        $scope.totalPageOfServant += count % limit >= 1 ? 1 : 0;
        var start = ($scope.currentPageOfServant - 2) >= 1 ? $scope.currentPageOfServant - 2 : 1;
        var end = ($scope.currentPageOfServant + 2) <= $scope.totalPageOfServant ? $scope.currentPageOfServant + 2 : $scope.totalPageOfServant;
        for (var i = start; i <= end; i++) {
            $scope.pageListOfServant.push({
                number: i,
                active: i == $scope.currentPageOfServant ? 'active' : ''
            });
        }
    };
    $scope.changePageOfServant = function (page) {
        if (page == 0) {
            page = 1;
        }
        $scope.selectedPageOfServant = page;
        manager = JSON.parse(localStorage.getItem(sessionStorage.getItem("who") + "manager"));
        if (manager != undefined && manager.isPension) {
            $scope.searchOfServant.manager_group_id = manager.manager_group_id;
        }
        servantService.searchList($scope.searchOfServant, $scope.limitOfServant, $scope.selectedPageOfServant, $scope.app_id, function (json) {
            $scope.servantList = json['list'];
            $scope.countOfServant = json['count'];
            $scope.currentPageOfServant = page;
            $scope.getPageOfServant($scope.countOfServant);
        });
    };

    $scope.passOrder = function (order) {
        $scope.order = order;
        $scope.searchOfServant = {
            //servantstatus: "待岗",
            verifystatus: "已通过审核",
            serviceType3_code: $scope.order.serviceType3_code
        };
        $scope.getServantList();
    };
    $scope.setServant = function (servant) {
        $scope.order.selected_servant_id = servant.servant_id;
        $scope.order.selected_servant_name = servant.name;
        $scope.order = {};
        closeMod();
    };

    $scope.grab = function (order_id, servant_id) {
        if (servant_id == "") {
            alert("请选择服务人员");
        } else {
            var data = {
                servant_id: servant_id,
                servantstatus: '在岗'
            };
            servantService.save(data, function (d) {
                console.log(d);
            });
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/order/grab/' + order_id + '/' + servant_id,
                'success': function (d) {
                    console.log(d);
                    if (d.status == 1) {
                        alert("恭喜，抢单成功！");
                        $scope.getList($scope.search);
                    } else {
                        if (d.description) {
                            alert(d.description);
                        } else {
                            alert('网络原因，请求失败，请稍后重试');
                        }
                    }
                }
            });
        }
    };

    //获取服务类型列表
    $scope.getserviceType1 = function (code) {
        orderService.getServiceListByCode(code, function (d) {
            $scope.serviceList1 = d.list;
            $scope.serviceList2 = [];
            $scope.search.serviceType2 = null;
            $scope.serviceList3 = [];
            $scope.search.serviceType3 = null;
        });
    };
    $scope.getserviceType2 = function (code) {
        orderService.getServiceListByCode(code, function (d) {
            $scope.serviceList2 = d.list;
            $scope.serviceList3 = [];
            $scope.search.serviceType3 = null;
        });
    };
    $scope.getserviceType3 = function (code) {
        orderService.getServiceListByCode(code, function (d) {
            $scope.serviceList3 = d.list;
        });
    };
    $scope.getserviceType1('0');

    $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
        init();
    });

    $scope.filter_order = function (item) {
        /**
         * tag
         * 1 => 可抢单
         * 2 => 可受理
         * 3 =>  已被抢
         */
        var tag = 3;
        if (item.company_code == undefined || item.company_code == "" || item.company_code == null) {

            if (item.selected_company_code == manager.company_code) {
                tag = 2;
            } else if (item.selected_company_code == "") {
                tag = 1;
            } else {
                tag = 3;
            }
        } else if (item.company_code.indexOf(manager.company_code) > -1) {
            if (item.selected_company_code == "") {
                tag = 1;
            } else if (item.selected_company_code == manager.company_code) {
                tag = 2;
            } else {
                tag = 3;
            }
        } else {
            if (item.selected_company_code == manager.company_code) {
                tag = 2;
            } else {
                tag = 3;
            }

        }
        return tag;
    };
}

function orderEditController( $scope, $window, $location, $http,$routeParams,orderService){
	$scope.getOrderInfo=function(){
        $scope.modify_group_tag = false ;
        var data = {
            'order_id':$routeParams.order_id
        };
        baas_yl.call({
            'http': $http,
            'method': 'post',
            'data':data,
            'uri': 'order/orderList/info',
            'success': function(d) {
               $scope.order = d.orderinfo;
               $scope.order.tscore="";
               //console.log($scope.order.comments);
                $scope.dubanlist = d.dubanlist;//督办记录
                $scope.companylist = d.companylist;//受理企业列表
                $scope.historylist = d.historylist;  //订单操作记录
                if(typeof $scope.order.company != 'undefined'){
                    for( var i = 0; i < $scope.companylist.length; i ++ ){
                        for( var j = 0; j < $scope.order.company.length; j ++ ){
                            if( $scope.companylist[i].name == $scope.order.company[j] ){
                                $scope.companylist[i].chk = true;
                            }
                        }
                    }
                }
                if($scope.order.selected_company_code == "12349E"){
                    $scope.getCompanyNameList($scope.order.selected_company_code);
                    console.log($scope.companyNameList);
                }
                //初始化回访状态
                $scope.initVisit( $scope.order );
            }
        });
    }
    $scope.getOrderInfo();
    $scope.getCompanyNameList = function (company_code){
        var data = {
            '_id':'',
            company_code : company_code ,
            groupName : ''
        };
        baas_jz.call({
            'http' : $http,
            'method' : 'get',
            'uri' : 'manager/group/list',
            'data' : data,
            'success' : function(d){
                $scope.companyNameList = d['list'];
                console.log($scope.companyNameList);
            }
        });
    }
    $scope.submit_new_manager_group = function (order){
        var order_id = order.order_id;
        var manager_group_id = order.new_manager_group._id

        baas_yl.call({
            'http' : $http,
            'method' : 'post',
            'uri' :'order/orderList/assign/'+order_id+'/manager_group/'+manager_group_id,
            data : {
                group_app_id : friend_app_id
            },
            'success' : function(d){
                $scope.getOrderInfo();
                $scope.modify_group_tag = false ;
                //$scope.order.selected_manager_group_name = order.new_manager_group.groupName;
                //$scope.order.selected_manager_group_id = manager_group_id;
            }
        });
    }
    $scope.modify_group = function (){
        $scope.modify_group_tag = true ;
    };

    $scope.update = function(order){

        order.company = [];
        for( var i = 0; i < $scope.companylist.length; i ++ ){
            if( $scope.companylist[i].chk ){
                order.company.push( $scope.companylist[i].name );
            }
        }
       // var time=angular.element("#timeId").val();
       var myDate = new Date();
       var time=myDate.toLocaleString( );
       // var managerName=d.manager_account;
        if(order.score!=undefined && order.score!=""){
        	//order.status="已回访";
        	order.status="完成";
        }
        var data = {
            //'username':'admin',//当前登录的用户名
            'company':order.company,
            'name':order.name,
            'phone':order.phone,
            'address':order.address,
            'serviceType1':order.serviceType1,
            'serviceType2':order.serviceType2,
            'detail':order.detail,
            'duban_time':time,
            'duban_info':(order.duban != undefined && order.duban != '')?order.duban.info:'',
			'duban_name':$scope.manager.manager_account,
            'score':parseInt(order.score),
            'comments':order.comments,
            'reComments':order.reComments,
            'status':order.status,
            'order_id':$scope.order.order_id
        };
	        baas_yl.call({
	        'http': $http,
	        'method': 'post',
	        'data':data,
	        'uri': 'order/orderList/update',
	        'success': function(d) {
	            if(d){
	                alert("更新成功");
	                $location.path( '/order' );
	            }else{
	                alert("更新失败");
	           }
	        }
	     });
	}
    $scope.endOrder = function (order){
        if(typeof order.endComments == "undefined" || order.endComments == ""){
            alert("请填写终止原因");
            return ;
        }
            var params = {
            'status': "终止订单",
            'order_id': order.order_id,
            'reason':order.endComments
        }
        orderService.update(params,function(json){
           if(json){
               alert("订单已被终止！");
           } else{
               alert("终止失败");
           }
        });
    }
    $scope.initVisit = function( order ){
        $scope.order.visit_type = '回访失败';
        $scope.order.visit_success_type = 0;
        if(order.return_visit_list != undefined ){
            for( var i = 0; i < order.return_visit_list.length; i ++ ){
                if(order.return_visit_list[i].type == '回访成功'){
                    $scope.order.visit_success_type = 1;
                }
            }
        }

    };
    /**
     * 添加回访记录
     */
    $scope.returnVisitStatus = 'normal';
    $scope.returnVisit = function( order ){

        //visit.type = '回访失败';
        var visit = {
            type : order.visit_type,
            reason : order.reComments,
            source : '养老',
            order : {
                reComments      : order.reComments,
                score           : order.score
            }
        };
        if( order.visit_type == '回访成功' ){
            visit.order.status = '完成';
        }
        $scope.returnVisitStatus = 'doing';
        orderService.returnVisit( order.order_id, visit, function( json ){
            $scope.returnVisitStatus = 'normal';
            if(json){
                alert("更新成功");
                $scope.getOrderInfo();
            }else{
                alert("更新失败");
            }
        });
    }

}

//function orderAddController($scope, $window, $location, $http, $routeParams,orderService){
//	$scope.app_id = $routeParams.app_id;
//	$scope.getRegion = function(code){
//		orderService.serviceList(code,$scope.app_id,  function( json ){
//			console.log(json);
//			$scope.serviceTypes = json;
//        } );
//	};
//    $scope.getRegion(0);
//	$scope.getStreet = function(code) {
//        orderService.serviceList2(code,$scope.app_id,function( json ){
//            $scope.streets = json;
//        });
//    };
//    $scope.getArea = function(code) {
//        orderService.serviceList3(code,$scope.app_id,function( json ){
//            $scope.areas = json;
//        });
//    };
//
//    /*添加订单*/
//    $scope.edit = function(data) {
//		orderService.add(data, $scope.app_id, function(json) {
//			alert("添加订单成功！");
//			//$location.path( '/order' );
//		});
//	};
//
//}

function    orderAddController( $scope, $routeParams,$window, $location, $http,orderService, callCenterService){
    $scope.app_id = $routeParams.app_id;
    $scope.managerType = JSON.parse(localStorage.getItem(sessionStorage.getItem("who") + "manager")).type_code;

    $scope.order={
        is_trial:0
    };
    //获取服务类型列表
    $scope.getserviceType1 = function(code){
        orderService.serviceListAll(code,function(d){
            $scope.serviceList1 = d.list;
            $scope.order.is_trial="0";
            $scope.serviceList3=[];

        });
    }
    $scope.getserviceType2 = function(code){
        orderService.serviceListAll(code,function(d){
            $scope.serviceList2 = d.list;
            $scope.filterCompanyList = '';
            $scope.order.is_trial="0";
            $scope.serviceList3=[];
        });
    }
    $scope.getserviceType3 = function(code){
        orderService.serviceListAll(code,function(d){
            $scope.serviceList3 = d.list;
            $scope.filterCompanyList = [];
            $scope.order.is_trial="0";
        });
    }

    //获取公司列表 By Nie
    $scope.getCompanyList = function (code) {
        callCenterService.getCompany(code, $scope.app_id, function (json) {
            $scope.companyList = json['list'];
        });
    };
    $scope.getCompanyList();

    $scope.getserviceType1('0');
    $scope.backSel=function(){
        for( var i = 0; i < $scope.filterCompanyList.length; i ++ ){
            $scope.filterCompanyList[i].chk = !($scope.filterCompanyList[i].chk );
        }
    }
    /*添加订单*/
    $scope.edit = function(data) {
        data.time=angular.element("#time").val();
        data.company_code=[];
        if(data.name==""|| typeof data.name==undefined|| !data.name  ){
            alert("请输入联系人");
            return;
        }
        if(data.phone==""|| typeof data.phone==undefined|| !data.phone  ){
            alert("请输入联系人电话");
            return;
        }
        if(data.serviceType3==""|| typeof data.serviceType3==undefined|| !data.serviceType3  ){
            alert("请选择服务项目");
            return;
        }
        for( var i = 0; i < $scope.filterCompanyList.length; i ++ ){
            if($scope.filterCompanyList[i].chk){
                data.company_code.push($scope.filterCompanyList[i].code);
            }
        }
        var manager = JSON.parse( localStorage.getItem(sessionStorage.getItem("who")+"manager") );
        if( manager.company_filter_type == "company" ){
            if(data.acceptType == "self"){

                if((manager.serviceType3_code.toString()).indexOf(data.serviceType3.code)<0){
                    alert("您选择的服务项目【"+data.serviceType3.title+"】不在自有服务里，无法自己受理，请放入抢单池");
                    return;
                }
                data.selected_company_code = manager.company_code;
                data.selected_company_name = manager.company_name;
                data.status = '已接单';
                if( manager.isPension ){
                    data.selected_manager_group_id = manager.manager_group_id;
                }
                data.fx =0;
                data.company_code.push(manager.company_code);
            }else{
                if($scope.filterCompanyList.length==0){
                    alert("您选择的服务项目【"+data.serviceType3.title+"】，没有企业能提供服务，无法放入抢单池，请重新选择");
                    return;
                }
                for( var i = 0; i < $scope.filterCompanyList.length; i ++ ){
                    data.company_code.push($scope.filterCompanyList[i].code);
                }
            }
        }

        //Admin发布订单 By Nie
        if ($scope.managerType === 'admin') {
            if (typeof data.selected_company === 'undefined' || !data.selected_company) {
                alert('请选择受理企业！');
                return;
            }
            data.selected_company_code = typeof data.selected_company.code === 'undefined' || !data.selected_company.code ? '' : data.selected_company.code;
            data.selected_company_name = typeof data.selected_company.name === 'undefined' || !data.selected_company.name ? '' : data.selected_company.name;
            data.selected_company_phone = typeof data.selected_company.telephone === 'undefined' || !data.selected_company.telephone ? '' : data.selected_company.telephone;
        }

        if(data.company_code.length==0){
            alert("请至少选择一个服务商");
            return;
        }
        data.serviceType1_code=(data != ''&& data != undefined && data.serviceType1!=undefined)?data.serviceType1.code:'';
        data.serviceType1_title=(data != ''&& data != undefined && data.serviceType1!=undefined)?data.serviceType1.title:'';
        data.serviceType2_code=(data != ''&& data != undefined && data.serviceType2!=undefined)?data.serviceType2.code:'';
        data.serviceType2_title=(data != ''&& data != undefined && data.serviceType2!=undefined)?data.serviceType2.title:'';
        data.serviceType3_code=(data != ''&& data != undefined && data.serviceType3!=undefined)?data.serviceType3.code:'';
        data.serviceType3_title=(data != ''&& data != undefined && data.serviceType3!=undefined)?data.serviceType3.title:'';
        data.serviceType1= (data != ''&& data != undefined && data.serviceType1!=undefined)?data.serviceType1.code:'';
        data.serviceType2= (data != ''&& data != undefined && data.serviceType2!=undefined)?data.serviceType2.code:'';
        data.serviceType3= (data != ''&& data != undefined && data.serviceType3!=undefined)?data.serviceType3.code:'';
        orderService.addOrder(data, $scope.app_id, function(json) {
            alert("添加订单成功！");
            $location.path( '/order/company' );
        });
    };
    $scope.getFilterCompany = function (serviceType3){
        if(serviceType3==""|| typeof serviceType3==undefined|| !serviceType3  ){
            $scope.filterCompanyList="";
            $scope.order.is_trial=0;
        }else{
            //判断是否试工
            if(serviceType3["shigong"]=="是"){
                $scope.order.is_trial="1";
            }else{
                $scope.order.is_trial="0";
            }
            var code=serviceType3.code;
            orderService.searchCompanyList(code,function(d){
                $scope.filterCompanyList=d.list
                if(typeof $scope.filterCompanyList != 'undefined'){
                    for( var i = 0; i < $scope.filterCompanyList.length; i ++ ){
                        $scope.filterCompanyList[i].chk = true;
                    }
                }
            });
        }
    };




}

function orderReservationController( $scope, $rootScope,$window, $location, $http, $routeParams, rsvService ,orderService){
    $scope.app_id = $routeParams.app_id;
    $scope.serviceJosn1={};
    $scope.serviceJosn2={};
    $scope.order = {};
    $scope.new_reservation = {};
    $scope.searchData = {
        limit: 20,
        page: 1
    };
    var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
    if(manager.isWX){//微信修改
        $scope.searchData.limit=10;
    }
    if(manager.company_code!=undefined){
        $scope.searchData.selected_company_code=manager.company_code;
    }
    if(manager.isCallCenter){
        $scope.searchData.selected_company_code="";
    }
    $scope.getList = function(){
        rsvService.list($scope.searchData, function( json ){
            $scope.list = json['list'];
            $scope.count = json['count'];
            $scope.currentPage = 1;
            $scope.getPage(json['count']);
        });
    };
    $scope.getList();
    //预约订单查询 by gxl 20151019

    $scope.query = function(search){
        //console.log(search.username.replace(/\s/g, ""));
        $scope.selectedPage = 1;
        if(search.orderstatus!=undefined&&search.orderstatus==""){
            search.orderstatus=undefined;
        }
        if(search.username!=undefined&&search.username==""){
            search.username=undefined;
        }
        if(search.telephone!=undefined&&search.telephone==""){
            search.telephone=undefined;
        }
        if(search.service1==undefined){
            search.service2=undefined;
            search.service3=undefined;
        }
        if(search.service2==undefined){
            search.service3=undefined;
            //search.service3=undefined;
        }
        //search.birthday=angular.element("#birthday").val();
        $scope.time=angular.element("#create_time").val();
        $scope.time1=angular.element("#time").val();
        $scope.searchData={
            limit: 20,
            selected_company_code:"",
            page: 1,
            name:(search != ''&& search != undefined&&search.username!= undefined)?search.username.replace(/\s/g, ""):undefined,
            phone:(search != ''&& search != undefined&&search.telephone!= undefined)?search.telephone.replace(/\s/g, ""):undefined,
            create_time:($scope.time != ''&& $scope.time!= undefined)?$scope.time:undefined,
            time:($scope.time1 != ''&& $scope.time1 != undefined)?$scope.time1:undefined,
            serviceType1_code: (search != ''&& search != undefined&&search.service1!= undefined)?search.service1.code:undefined,
            serviceType2_code: (search != ''&& search != undefined&&search.service2!= undefined)?search.service2.code:undefined,
            serviceType3_code: (search != ''&& search != undefined&&search.service3!= undefined)?search.service3.code:undefined,
            status:(search != ''&& search!= undefined)?search.orderstatus:undefined
        };
        manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
        if(manager.isWX){//微信修改
            $scope.searchData.limit=10;
        }
        if(manager.company_code!=undefined){
            $scope.searchData.selected_company_code=manager.company_code;
        }
        if(manager.isCallCenter){
            $scope.searchData.selected_company_code="";
        }

        rsvService.list($scope.searchData, function( json ){

            $scope.list = json.list;
            $scope.count = json.count;
            $scope.currentPage = 1;
            $scope.getPage(json.count);
        });
    };

    $scope.changePage = function(p) {
        $scope.searchData.page = p;
        rsvService.list($scope.searchData, function(json) {
            $scope.list = json.list;
            $scope.count = json.count;
            $scope.currentPage = p;
            $scope.getPage(json.count);
        });
    };
    $scope.getPage = function(count) {
        $scope.pageList = [];
        var limit = $scope.searchData.limit; //返回的条数
        $scope.totalPage = parseInt(count / limit); //总页数
        $scope.totalPage += count % limit >= 1 ? 1 : 0; //判断页数是否是整数
        var start = ($scope.currentPage - 2) >= 1 ? $scope.currentPage - 2 : 1; //首页
        var end = ($scope.currentPage + 2) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage; //尾页

        $scope.frontdotShow = start > 1 ? true : false; //前面的省略号
        $scope.backdotShow = end < $scope.totalPage ? true : false; //后面的省略号
        for (var i = start; i <= end; i++) {
            $scope.pageList.push({
                number: i,
                active: i == $scope.currentPage ? 'active' : ''
            }); //给点击的按钮添加class
        }
    };


    //获取服务类型列表
    $scope.getserviceType1 = function(code,code1){
        orderService.serviceList(code,function(d){
            var str="{";
            for (i=0;i<d.list.length;i++) {
                var item=d.list[i];
                str+="'"+item.code+"':'"+item.title+"'";
                str+=i<d.list.length-1?",":"";
            }
            str+="}";

            $scope.serviceJosn1=eval("("+str+")");
            $scope.serviceList1 = d.list;
            if(code1!='1'&& typeof code1 !="undefined"){
                $scope.filterCompanyList = [];
            }
        });
    }
    $scope.getserviceType2 = function(code,code1){
        if(code1!='1'&& typeof code1 !="undefined"){
            $scope.filterCompanyList = "";
            $scope.newOrder.is_trial="0";
            $scope.serviceList3="";
        }
        orderService.serviceList(code,function(d){
            var str="{";
            for (i=0;i<d.list.length;i++) {
                var item=d.list[i];
                str+="'"+item.code+"':'"+item.title+"'";
                str+=i<d.list.length-1?",":"";
            }
            str+="}";
            $scope.serviceJosn2=eval("("+str+")");
            $scope.serviceList2 = d.list;

        });
    }
    $scope.getserviceType3 = function(code,code1){
        if(code1!='1'&& typeof code1 !="undefined"){
            $scope.filterCompanyList = "";
        }
        orderService.serviceList(code,function(d){
            $scope.newOrder.is_trial="0";
            var str="{";
            for (i=0;i<d.list.length;i++) {
                var item=d.list[i];
                str+="'"+item.code+"':'"+item.title+"'";
                str+=i<d.list.length-1?",":"";
                if(item.code==$scope.newOrder.serviceType3_code){
                    if(item.shigong=="是"){
                        $scope.newOrder.is_trial="1";
                    }
                }
            }
            str+="}";
            $scope.serviceJosn3=eval("("+str+")");
            $scope.serviceList3 = d.list;


        });
    }

    $scope.backSel=function(){
        for( var i = 0; i < $scope.companylist.length; i ++ ){
            $scope.companylist[i].chk = !($scope.companylist[i].chk );
        }
    }
    /**
     *
     */
    $scope.af=0;
    $scope.clearServant=function(){
        delete $scope.newOrder["servant"];
        $scope.af=1;
    }

    $scope.editStatus = 0;

    $scope.edit = function( order ){

        $scope.rsvOrder=order;

        $scope.newOrder= {
            name:order.name,
            address: '',
            phone:order.phone,
            time:order.create_time,
            status:'待受理',
            reserve_id:order._id,
            selected_company_code:order.selected_company_code,
            serviceType1:order.serviceType1_code,
            serviceType2:order.serviceType2_code,
            serviceType3:order.serviceType3_code,
            serviceType1_code:order.serviceType1_code,
            serviceType1_title:order.serviceType1_title,
            serviceType2_code:order.serviceType2_code,
            serviceType2_title:order.serviceType2_title,
            serviceType3_code:order.serviceType3_code,
            serviceType3_title:order.serviceType3_title,
            selected_servant_id:order.servant_id,
            selected_servant_name:order.servant_name,
            attribute:order.attribute
        };
        $scope.newOrder.address += order.region != undefined ? order.region : '';
        $scope.newOrder.address += order.address != undefined ? order.address : '';

        if(order.servant!=""&&order.servant!=undefined)
            $scope.newOrder.servant=order.servant;
        $scope.getserviceType1('0','1');
        if(typeof($scope.newOrder.serviceType1)!="undefined"){
            $scope.getserviceType2($scope.newOrder.serviceType1_code,'1');
        }
        if(typeof($scope.newOrder.serviceType2)!="undefined"){
            $scope.getserviceType3($scope.newOrder.serviceType2_code,'1');
        }

        if(typeof($scope.newOrder.serviceType3_code)!="undefined"){
            $scope.getFilterCompany($scope.newOrder.serviceType3_code);
        }else{
            $scope.filterCompanyList = [];
        }

        $scope.editStatus = 1;
    };

    $scope.getFilterCompany = function (code){
        angular.forEach($scope.serviceList3,function(data,index,list){
            if(code == data.code){

                $scope.newOrder.serviceType3 = data.code;
                $scope.newOrder.serviceType3_code = data.code;
                $scope.newOrder.serviceType3_title=data.title;

                $scope.rsvOrder.serviceType3 = data.code;
                $scope.rsvOrder.serviceType3_code = data.code;
                $scope.rsvOrder.serviceType3_title = data.title;
                if(data["shigong"]=="是"){
                    $scope.newOrder.is_trial="1";
                }else{
                    $scope.newOrder.is_trial="0";
                }

            }

        });

        /* angular.forEach($scope.companylist,function(data,index,list){

         if(typeof data.serviceType3_code != "undefined" && data.serviceType3_code.indexOf(code) > -1){
         $scope.filterCompanyList.push(data);
         }
         });*/
        orderService.searchCompanyList(code,function(d){
            $scope.filterCompanyList=d.list
            angular.forEach($scope.filterCompanyList,function(data,index,list){
                data.chk=true;
            });
        });


    };


    $scope.cancelEdit = function( ){
        $scope.editStatus = 0;

    };

    $scope.delete = function( curr ){
        rsvService.delete(curr._id, $scope.app_id, function( json ){
            if( json.status ){
                $scope.getList();
            }else{
                alert(json.description);
            }

        });
    };

    $scope.addReservation = function( new_reservation ){
        rsvService.edit( 0, new_reservation, $scope.app_id, function(){
            $scope.editStatus = 0;
            $scope.getList();
            $scope.new_reservation = {};
        });
    };

    $scope.editReservation = function( order ){

        order.company_code = [];

        var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
        if(manager!=undefined&&manager.company_code!=undefined){
            order.company_code.push(manager.company_code);
            order.selected_company_code=manager.company_code;
            order.selected_company_name=manager.company_name;
            order.status="已接单";
        }else{
            for( var i = 0; i < $scope.filterCompanyList.length; i ++ ){
                if( $scope.filterCompanyList[i].chk ){
                    order.company_code.push( $scope.filterCompanyList[i].code );
                }
            }
        }
        order.time=angular.element("#yuyuetime").val();
        order.serviceType1_code = order.serviceType1;
        order.serviceType1_title = $scope.serviceJosn1[order.serviceType1];

        order.serviceType2_code = order.serviceType2;
        order.serviceType2_title = $scope.serviceJosn2[order.serviceType2];

        order.serviceType3_code = order.serviceType3;
        order.serviceType3_title=$scope.serviceJosn3[order.serviceType3];
        $scope.rsvOrder.status=1;

        if(order.company_code.length==0){
            alert("请至少选择一个服务商");
            return;
        }

        if(!order.serviceType3 || order.serviceType3==undefined|| order.serviceType3==""){
            alert("请选择服务项目");
            return;
        }
        rsvService.edit( $scope.rsvOrder._id, $scope.rsvOrder, $scope.app_id, function(){
            $scope.editStatus = 0;
            $scope.getList();

        });

        /*	order.selected_servant_id=order.servant!=undefined?order.servant._id.$id:"";
         order.selected_servant_name=order.servant!=undefined?order.servant.name:"";*/
        //order.servant!=undefined?delete order["servant"]:delete order["selected_servant_id"] delete order["selected_servant_name"];

        if(order.servant==undefined){
            delete order["selected_servant_id"] ;delete order["selected_servant_name"];
        }
        delete order["servant"];
        //预约订单id
        orderService.add(order, $scope.app_id, function(json) {
            //$location.path( '/order' );
            alert('预约通过！');
            closeMod();
        });

    };

    $scope.editReservationCompany = function( order ){
        order.company_code = [];

        var manager=JSON.parse(localStorage.getItem(sessionStorage.getItem("who")+"manager"));
        if(manager!=undefined&&manager.company_code!=undefined){
            order.company_code.push(manager.company_code);
            order.selected_company_code=manager.company_code;
            order.selected_company_name=manager.company_name;
            order.status="已接单";
        }else{
            for( var i = 0; i < $scope.companylist.length; i ++ ){
                if( $scope.companylist[i].chk ){
                    order.company_code.push( $scope.companylist[i].code );
                }
            }
        }
        order.time=angular.element("#yuyuetime").val();
        order.serviceType1_code= order.serviceType1;
        order.serviceType1_title= $scope.serviceJosn1[order.serviceType1];

        order.serviceType2_code= order.serviceType2;
        order.serviceType2_title= $scope.serviceJosn2[order.serviceType2];

        order.serviceType3_code=order.serviceType3;
        order.serviceType3_title=$scope.serviceJosn3[order.serviceType3];
        $scope.rsvOrder.status=1;
        rsvService.edit( $scope.rsvOrder._id, $scope.rsvOrder, $scope.app_id, function(){
            $scope.editStatus = 0;
            $scope.getList();

        });
        //预约订单id
        orderService.add(order, $scope.app_id, function(json) {
            alert('预约通过！');
            $location.path( '/order' );
            closeMod();
        });

    };

    $scope.updatersv = function( order ){

        order.status=0;
        rsvService.update( order._id, order, $scope.app_id, function(){
            $scope.editStatus = 0;
            $scope.getList();

        });

    };

    //获取服务类型列表
    //大类
    $scope.getserviceTypeNew1 = function(code){
        var data = {
            'code':(code != ''&& code  != undefined)?code:''
        };
        baas_jz.call({
            'http': $http,
            'method': 'post',
            'data':data,
            'uri': 'order/orderList/serviceList',
            'success': function(d) {
                $scope.serviceList = d.list;
            }
        });


    }
    //中类
    $scope.getserviceTypeNew2 = function(code){
        var data = {
            'code':(code != ''&& code  != undefined)?code:''
        };
        baas_jz.call({
            'http': $http,
            'method': 'post',
            'data':data,
            'uri': 'order/orderList/serviceList',
            'success': function(d) {
                $scope.serviceList2 = d.list;
            }
        });


    }
    //小类
    $scope.getserviceTypeNew3 = function(code){
        var data = {
            'code':(code != ''&& code  != undefined)?code:''
        };
        baas_jz.call({
            'http': $http,
            'method': 'post',
            'data':data,
            'uri': 'order/orderList/serviceList',
            'success': function(d) {
                $scope.serviceList3 = d.list;
            }
        });


    }
    $scope.getserviceTypeNew1('0');


    $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
        init();
    });

}

function orderDetailController( $scope, $window, $location, $http,$routeParams,orderService){
    $scope.getOrderInfo=function(){
        var data = {
            'order_id':$routeParams.order_id
        };
        baas_jz.call({
            'http': $http,
            'method': 'post',
            'data':data,
            'uri': 'order/orderList/info',
            'success': function(d) {
                $scope.order = d.orderinfo;
                console.log($scope.order);
                $scope.order.remarkUser="";
                console.log(d.orderinfo);
                $scope.dubanlist = d.dubanlist;//督办记录
                $scope.companylist = d.companylist;//受理企业列表
                $scope.historylist = d.historylist;  //订单操作记录
                console.log ($scope.historylist);
                if(typeof $scope.order.company != 'undefined'){
                    for( var i = 0; i < $scope.companylist.length; i ++ ){
                        for( var j = 0; j < $scope.order.company.length; j ++ ){
                            if( $scope.companylist[i].name == $scope.order.company[j] ){
                                $scope.companylist[i].chk = true;
                            }
                        }
                    }
                }
                if(typeof $scope.order.remarks != 'undefined'){
                    var remarks=$scope.order.remarks;
                    var remarkList=remarks.toString().split("##");
                    $scope.remarkList=new Array();
                    for (i=0;i<remarkList.length;i++) {
                        $scope.remarkList.push({context:remarkList[i],time:'',user:''});
                    }
                }
                if(typeof $scope.order.remarkTimes != 'undefined'){
                    var remarkTimes=$scope.order.remarkTimes;
                    var remarkTimeList=remarkTimes.toString().split("##");
                    for (i=0;i<remarkTimeList.length;i++) {
                        $scope.remarkList[i].time=remarkTimeList[i];
                    }
                }
                if(typeof $scope.order.remarkUsers != 'undefined'){
                    var remarkUsers=$scope.order.remarkUsers;
                    var remarkUserList=remarkUsers.toString().split("##");
                    for (i=0;i<remarkUserList.length;i++) {
                        $scope.remarkList[i].user=remarkUserList[i];
                    }
                }
                $scope.initSettlement( $scope.order );
            }

        });

        data = {
            'type':'退单'
        };
        baas_jz.call({
            'http': $http,
            'method': 'get',
            'data':data,
            'uri': 'order/order/history/list/'+$routeParams.order_id,
            'success': function(d) {
                $scope.backOrderList=d.list;
            }
        });
    }
    $scope.getOrderInfo();
    //获取服务类型列表
    $scope.getserviceType1 = function(code){
        orderService.serviceList(code,function(d){
            $scope.serviceList1 = d.list;
        });
    }
    $scope.getserviceType2 = function(code){
        orderService.serviceList(code,function(d){
            $scope.serviceList2 = d.list;
        });
    }
    $scope.getserviceType3 = function(code){
        orderService.serviceList(code,function(d){
            $scope.serviceList3 = d.list;
        });
    }
    $scope.saveRemark=function(order,remarkUser){
        console.log(order.remark);
        if(typeof order.remark == 'undefined'||order.remark==""){
            alert("请输入备注");
            return;
        }
        if(typeof order.remarks == 'undefined'){
            order.remarks="";
            order.remarkTimes="";
            order.remarkUsers="";
        }
        var myDate = getLocalDateTime("yyyy-MM-dd HH:mm:ss");
        order.remarks=order.remarks+order.remark+"##";
        order.remarkTimes=order.remarkTimes+myDate.toLocaleString()+"##";
        var manager = JSON.parse( localStorage.getItem(sessionStorage.getItem("who")+"manager") );
        order.remarkUsers=order.remarkUsers+manager.manager_account+"##";
        var new_order={
            order_id:order.order_id,
            remarks:order.remarks,
            remarkTimes:order.remarkTimes,
            remarkUsers:order.remarkUsers
        }
        orderService.update(new_order,function(json){
            $scope.getOrderInfo();
        });
    }
    // by gxl 20150918
    $scope.setNewContractInfo=function (order){
        $scope.ContractInfo=order;

    }
    //合同信息传送到接口(追加试工合同)
    $scope.setNewContractProbation = function(setInfo) {
        setInfo.time2=angular.element('#time2').val();

        console.log("setInfo.number="+setInfo.number);
        console.log("setInfo.time1="+setInfo.time1);
        console.log("setInfo.time2="+setInfo.time2);
        console.log($scope.order);
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.number == 'undefined' ||
            setInfo.number.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert('协议编号不能为空！');
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.time1 == 'undefined' ||
            setInfo.time1.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert('试工期不能为空！');
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.time2 == 'undefined' ||
            setInfo.time2.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert("试工开始时间不能为空！");
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.name == 'undefined' ||
            setInfo.name.replace(/^(\s+)|(\s+)$/,'').length == 0){
            alert("客户姓名不能为空！");
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.address == 'undefined' ||
            setInfo.address.replace(/^(\s+)|(\s+)$/,'').length == 0){
            alert("甲方地址不能为空！");
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.selected_company_phone == 'undefined' ||
            setInfo.selected_company_phone.replace(/^(\s+)|(\s+)$/,'').length == 0){
            alert("丙方联系方式不能为空！");
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.probation_money == 'undefined' ){
            alert("试工期工资不能为空！");
            return;
        }
        var data = {
            agreement_probation_number:setInfo.number,
            agreement_probation_jia_name:setInfo.name,
            agreement_probation_jia_address:setInfo.address,
            agreement_probation_jia_phone:setInfo.phone,
            agreement_probation_yi_name:setInfo.selected_servant_name,
            agreement_probation_yi_phone:setInfo.selected_servant_phone,
            agreement_probation_bing_name:setInfo.selected_company_name,
            agreement_probation_bing_phone:setInfo.selected_company_phone,
            agreement_service_type:setInfo.serviceType2_title,
            agreement_probation_days:setInfo.time1,
            agreement_probation_start:setInfo.time2,
            agreement_probation_foregift:setInfo.foregift,
            agreement_probation_money:setInfo.probation_money
        };
        console.log($scope.order);
        orderService.setContractProbationInfo(data,setInfo.order_id,function(d){
            if(d){
                alert("追加试工合同成功！");
                $scope.getContractProbation();
                //delete $scope.ContractInfo;
                $scope.ContractInfo.number="";
                $scope.ContractInfo.time1="";
                $scope.ContractInfo.time2="";
                $scope.ContractInfo.foregift="";
                closeMod();
            }else{
                alert("更新失败");
            }
        });
    };
    //生成正式合同 by gxl  20150918

    $scope.setFormalContractProbation=function(setInfo) {

        if( typeof setInfo == 'undefined' ||
            typeof setInfo.number == 'undefined' ||
            setInfo.number.replace(/^(\s+)|(\s+)$/,'').length == 0){
            alert('协议编号不能为空！');
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.name == 'undefined' ||
            setInfo.name.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert("客户姓名不能为空！");
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.address == 'undefined' ||
            setInfo.address.replace(/^(\s+)|(\s+)$/,'').length == 0){
            alert("甲方地址不能为空！");
            return;
        }
        if( typeof setInfo == 'undefined' ||
            typeof setInfo.selected_company_phone == 'undefined' ||
            setInfo.selected_company_phone.replace(/^(\s+)|(\s+)$/,'').length == 0){

            alert("丙方联系方式不能为空！");
            return;
        }

        setInfo.formal_start=angular.element('#formal_start').val();
        setInfo.formal_end=angular.element('#formal_start').val();
        setInfo.start=angular.element('#start').val();
        setInfo.end=angular.element('#end').val();
        setInfo.sign_time=angular.element('#sign_time').val();

        var data = {
            agreement_formal_number:(setInfo != ''&& setInfo != undefined && setInfo.number!=undefined)?setInfo.number:'',
            agreement_formal_jia_name:(setInfo != ''&& setInfo != undefined && setInfo.name!=undefined)?setInfo.name:'',
            agreement_formal_jia_address:(setInfo != ''&& setInfo != undefined && setInfo.address!=undefined)?setInfo.address:'',
            agreement_formal_jia_id:(setInfo != ''&& setInfo != undefined && setInfo.jia_id!=undefined)?setInfo.jia_id:'',
            agreement_formal_jia_phone:(setInfo != ''&& setInfo != undefined && setInfo.phone!=undefined)?setInfo.phone:'',
            agreement_formal_yi_name:(setInfo != ''&& setInfo != undefined && setInfo.selected_servant_name!=undefined)?setInfo.selected_servant_name:'',
            agreement_formal_yi_phone:(setInfo != ''&& setInfo != undefined && setInfo.selected_servant_phone!=undefined)?setInfo.selected_servant_phone:'',
            agreement_formal_yi_id:(setInfo != ''&& setInfo != undefined && setInfo.yi_id!=undefined)?setInfo.yi_id:'',
            agreement_formal_yi_address:(setInfo != ''&& setInfo != undefined && setInfo.yi_address!=undefined)?setInfo.yi_address:'',
            agreement_formal_bing_name:(setInfo != ''&& setInfo != undefined && setInfo.selected_company_name!=undefined)?setInfo.selected_company_name:'',
            agreement_formal_bing_address:(setInfo != ''&& setInfo != undefined && setInfo.bing_address!=undefined)?setInfo.bing_address:'',
            agreement_formal_bing_phone:(setInfo != ''&& setInfo != undefined && setInfo.selected_company_phone!=undefined)?setInfo.selected_company_phone:'',
            agreement_service_type:(setInfo != ''&& setInfo != undefined && setInfo.serviceType2_title!=undefined)?setInfo.serviceType2_title:'',
            agreement_formal_requirements:(setInfo != ''&& setInfo != undefined && setInfo.formal_requirements!=undefined)?setInfo.formal_requirements:'',
            agreement_formal_place:(setInfo != ''&& setInfo != undefined && setInfo.formal_place!=undefined)?setInfo.formal_place:'',
            agreement_formal_start:(setInfo != ''&& setInfo != undefined && setInfo.formal_start!=undefined)?setInfo.formal_start:'',
            agreement_formal_end:(setInfo != ''&& setInfo != undefined && setInfo.formal_end!=undefined)?setInfo.formal_end:'',
            agreement_monthly_salary:(setInfo != ''&& setInfo != undefined && setInfo.monthly_salary!=undefined)?setInfo.monthly_salary:'',
            agreement_pay_time:(setInfo != ''&& setInfo != undefined && setInfo.pay_time!=undefined)?setInfo.pay_time:'',
            agreement_pay_method:(setInfo != ''&& setInfo != undefined && setInfo.pay_method!=undefined)?setInfo.pay_method:'',
            agreement_intermediary_fee:(setInfo != ''&& setInfo != undefined && setInfo.intermediary_fee!=undefined)?setInfo.intermediary_fee:'',
            agreement_others:(setInfo != ''&& setInfo != undefined && setInfo.others!=undefined)?setInfo.others:'',
            agreement_rest_days:(setInfo != ''&& setInfo != undefined && setInfo.rest_days!=undefined)?setInfo.rest_days:'',
            agreement_start:(setInfo != ''&& setInfo != undefined && setInfo.start!=undefined)?setInfo.start:'',
            agreement_end:(setInfo != ''&& setInfo != undefined && setInfo.end!=undefined)?setInfo.end:'',
            agreement_sign_time:(setInfo != ''&& setInfo != undefined && setInfo.sign_time!=undefined)?setInfo.sign_time:''
        };

        orderService.setNewFormalContractProbationInfo(data,setInfo.order_id,function(d){
            if(d){
                alert("保存合同成功！");
                $scope.getFormalContract();
                console.log($scope.ContractInfo);
                $scope.ContractInfo.number='';
                $scope.ContractInfo.name='';
                $scope.ContractInfo.address='';
                $scope.ContractInfo.jia_id='';
                $scope.ContractInfo.phone='';
                $scope.ContractInfo.selected_servant_name='';
                $scope.ContractInfo.selected_servant_phone='';
                $scope.ContractInfo.yi_id='';
                $scope.ContractInfo.yi_address='';
                $scope.ContractInfo.selected_company_name='';
                $scope.ContractInfo.bing_address='';
                $scope.ContractInfo.selected_company_phone='';
                $scope.ContractInfo.serviceType2_title='';
                $scope.ContractInfo.formal_requirements='';
                $scope.ContractInfo.formal_place='';
                $scope.ContractInfo.formal_start='';
                $scope.ContractInfo.formal_end='';
                $scope.ContractInfo.monthly_salary='';
                $scope.ContractInfo.pay_time='';
                $scope.ContractInfo.pay_method='';
                $scope.ContractInfo.intermediary_fee='';
                $scope.ContractInfo.others='';
                $scope.ContractInfo.rest_days='';
                $scope.ContractInfo.start='';
                $scope.ContractInfo.end='';
                $scope.ContractInfo.sign_time='';
                closeMod();
            }else{
                alert("更新失败");
            }
        });

    }

    $scope.updateOrderStatus = function(order_id,status) {
        var data = {
            'status':status,
            //'reason':"",
            'order_id':order_id
        };
        orderService.update(data,function(d){
            if(d){
                $scope.getOrderInfo();

            }else{
                alert("更新失败");
            }
        });
    };
    //获得正式合同 list by gxl 20150922
    $scope.getFormalContract=function(){

        var data = {
            'order_id':$routeParams.order_id
        };

        baas_jz.call({
            'http': $http,
            'method': 'post',
            'data':data,
            'uri': 'order/order/list/formal/agreement',
            'success': function(d) {
                $scope.FormalList=d.list;
            }
        });
    }
    //获得试工合同 list by gxl 20150922
    $scope.getContractProbation=function(){

        var data = {
            'order_id':$routeParams.order_id
        };

        baas_jz.call({
            'http': $http,
            'method': 'post',
            'data':data,
            'uri': 'order/order/list/probation/agreement',
            'success': function(d) {
                $scope.ProbationList=d.list
            }
        });
    }

    $scope.getContractProbation();
    $scope.getFormalContract();

    // 结算:获得总价格
    $scope.settlement = {};
    $scope.initSettlement = function( order ){

        if( typeof order.card_number != 'undefined' && order.card_number != '' ){
            $scope.findCard(order);
        }else{
            $scope.initSettlementData(order);
        }

    };
    $scope.findCard = function( order ){
        $scope.card = {};
        orderService.find_card(order.card_number , function(json) {
            if( json.length > 0){
                $scope.card = json[0];
            }else{
                $scope.card.fund = 0;
                console.log('老年卡不存在');
            }
            $scope.initSettlementData(order);
        });
    };
    $scope.initSettlementData = function( order ){
        order.settlement_extraPrice = (typeof order.settlement_extraPrice == 'undefined')?0:order.settlement_extraPrice;
        $scope.settlement.settlement_status = order.settlement_status;
        $scope.settlement.settlement_description = order.settlement_description;
        //单位价格
        $scope.settlement.settlement_unit = order.settlement_unit;
        $scope.settlement.settlement_price = $scope.toNumber( order.settlement_price, 0);
        // 单位次数
        $scope.settlement.settlement_service_times = $scope.toNumber( order.settlement_service_times, 1);
        //额外追加的钱
        if( order.settlement_extraPrice >= 0 ){
            $scope.settlement.extraPriceFlag = 'add';
            $scope.settlement.settlement_extraPrice_add = order.settlement_extraPrice;
            $scope.settlement.settlement_extraPrice_reduce = 0;
        }else{
            $scope.settlement.extraPriceFlag = 'reduce' ;
            $scope.settlement.settlement_extraPrice_reduce = Math.abs( order.settlement_extraPrice );
            $scope.settlement.settlement_extraPrice_add = 0;
        }
        $scope.settlement.settlement_extraPrice = !isNaN(order.settlement_extraPrice) && typeof order.settlement_extraPrice != 'undefined'?
            order.settlement_extraPrice.toFixed(2):0;

        //$scope.getServiceType( $scope.item );
        //结算完成
        if( typeof $scope.settlement.settlement_status != 'undefined' &&
            $scope.settlement.settlement_status == 1 ){
            //$scope.settlement_status = 1;
            //老人卡支付的钱
            $scope.settlement.settlement_card_fund = !isNaN(order.settlement_card_fund) && typeof order.settlement_card_fund != 'undefined'?
                order.settlement_card_fund.toFixed(2):0;
            //支付的现金
            $scope.settlement.settlement_cash = !isNaN(order.settlement_cash) && typeof order.settlement_cash != 'undefined'?
                order.settlement_cash.toFixed(2):0;
            $scope.settlement.settlement_total = !isNaN(order.settlement_total) && typeof order.settlement_total != 'undefined'?
                order.settlement_total.toFixed(2):0;
        }else{
            $scope.settlement.settlement_status = 0;
            $scope.getPriceTotal( $scope.settlement );
        }
        //$scope.settlement_status = 1;
    };

    $scope.toNumber = function( thisValue, defaultNumber ){

        var res = thisValue != undefined ? parseInt( thisValue) : defaultNumber;
        res = !isNaN( res ) ? res : defaultNumber;
        return res;
    };

    $scope.changeExtraPrice = function( flag ){
        $scope.settlement.extraPriceFlag = flag;
        $scope.getPriceTotal($scope.settlement);
    };


    $scope.getPriceTotal = function( settlement ){

        settlement.settlement_service_times = $scope.toNumber(settlement.settlement_service_times,1);
        settlement.settlement_service_times = settlement.settlement_service_times < 1 ? 1 : settlement.settlement_service_times;
        settlement.settlement_extraPrice = settlement.extraPriceFlag == 'add' ?
            settlement.settlement_extraPrice_add : settlement.settlement_extraPrice_reduce;
        settlement.settlement_extraPrice = Number(settlement.settlement_extraPrice);
        settlement.settlement_extraPrice = settlement.extraPriceFlag == 'add' ?
            settlement.settlement_extraPrice  : - settlement.settlement_extraPrice;
        settlement.settlement_total = settlement.settlement_price * settlement.settlement_service_times + settlement.settlement_extraPrice;
        settlement.settlement_cash = settlement.settlement_total - ($scope.card!=undefined?$scope.card.fund:0) ; // 现金
        settlement.settlement_cash = settlement.settlement_cash.toFixed(2);
        if( settlement.settlement_cash < 0 ){
            settlement.settlement_cash = 0;
            settlement.settlement_card_fund = settlement.settlement_total;
        }else{
            settlement.settlement_card_fund = $scope.card!=undefined?$scope.card.fund:0;
        }
    };

    // 创建交易
    $scope.createTransaction = function( data, fn ){
        baas_yl.call({
            'http': $http,
            'method': 'post',
            'uri': 'card/index/transaction/' + $scope.card.card_id ,
            'data': {
                type : 'pay',
                fund : data.settlement_card_fund,
                description : data.settlement_description != undefined ? data.settlement_description : '服务站代扣款',
                status : '1'
            },
            'success': function (json) {
                if (typeof fn == 'function' && json.status ) {
                    data.transaction_no = json.transaction_no;
                    fn( data );
                }
            }
        });
    };

    // 调用完成订单API
    $scope.finish = function( data ){
        var lat = 0;
        var lng = 0;
        var paramsData = {
            selected_servant_lat : lat,
            selected_servant_lng : lng,
            start_time : 0,
            settlement_service_times : data.settlement_service_times,
            settlement_extraPrice : data.settlement_extraPrice,
            settlement_description : data.settlement_description,
            'pay':1
        };
        if( typeof data.transaction_no != 'undefined' ){
            paramsData.transaction_no = data.transaction_no;
        }
        if( $scope.order.selected_servant_id  == undefined){
            alert( '该订单还没有制定服务人员' );
            return;
        }
        baas_jz.call({
            'http': $http,
            'method': 'post',
            'uri': 'order/order/servant/' + $scope.order.selected_servant_id + '/finish/'+$scope.order.order_id,
            'data' : paramsData,
            'success': function(d) {
                if(d.status){
                    alert("更新成功");
                    //$scope.item.status = '完成';
                    $scope.getOrderInfo();
                    //$scope.find_one( $scope.order_id );
                }else{
                    alert(d.description);
                }
            }
        });
    };

    //订单支付(服务站使用)
    $scope.payOrder = function( settlement ){
        if( settlement.settlement_total <= 0 ){
            alert( '总价必须大于零' );
            return;
        }

        if(typeof $scope.card.card_id != 'undefined' && settlement.settlement_card_fund >= 0 ){
            $scope.createTransaction( settlement, $scope.finish );
        }else{
            $scope.finish( settlement );
        }
    };

    //订单支付设置(企业使用)
    $scope.updateSettlement = function( order ){
        var param = {
            'order_id':order.order_id,
            'settlement_total':order.settlement_total,
            'settlement_status': 1
        };
        orderService.update( param, function( json ){
            if( json ){
                alert('设置成功');
                $scope.getOrderInfo();
            }
        } );
    }
}